vue-router是一個插件包,要先用npm進行安裝
1、安裝vue-router
npm install vue-routeryarn add vue-router
2、引入注冊vue-router
import Vue from 'vue'import VueRouter from 'vue-router'Vue.use(VueRouter)
3、鏈接跳轉
<router-link to='/home'></router-link> //你可以在template中使用它實現一個可點擊跳轉到home.vue的 a 標簽this.$router.push('/about'); //在methods方法中跳轉到about頁面this.$router.go('-1'); //在js中返回上一個頁面4、經常用到
this.$route.params.name //在js中獲取路由的參數.router-link-active //當前選中路由的匹配樣式$route.query //獲取查詢參數$route.hash //哈希
5、路由配置
export default new Router({ routes:[ { //第一層是頂層路由,頂層路由中的router-view中顯示被router-link選中的子路由 path:'/', name:'Home', component:'Home' },{ path:'/user/:id', //www.xxx.com/user/cai name:'user', //:id是動態路徑參數 component:'user', children:[ { path:'userInfo', //www.xxx.com/user/cai/userInfo component:'userInfo' //子路由將渲染到父組件的router-view中 },{ path:'posts', component:'posts' } ] } ]})Vue.use(Router);6、路由參數方式變化時,重新發出請求并更新數據
//比如:用戶一切換到用戶二, 路由參數改變了,但組件是同一個,會被復用// 從 /user/cai 切到 /user/wan
在User組件中:
//方法1: watch:{ '$route'(to,from){ //做點什么,比如:更新數據 } }//方法二: beforeRouteUpdate(to,from,next){ //同上 }7、編程式導航
router.push({name:'user',params:{userId:'123'}}) //命名路由導航到user組件<router-link :to='{name:'user',params:{userId:'123'}}'>用戶</router-link>router.push({path:'register',query:{plan:'cai'}}) //query查詢參數router.push({path:`/user/${userId}`}) //queryrouter.push(location,onComplete,onAbort)router.replace() //替換router.go(-1)8、命名視圖
//當前組件中只有一個 router-view 時,子組件默認渲染到這里<router-view class='default'></router-view><router-view class='a' name='left'></router-view><router-view class='b' name='main'></router-view>routes:[ { path:'/', components:{ default:header, left:nav, main:content //content組件會渲染在name為main的router-view中 } }]//嵌套命名視圖就是:子路由+命名視圖9、重定向與別名
const router = new VueRouter({ routes: [ { path: '/a', redirect: '/b' }, { path: '/b', redirect: { name: 'foo' }}, //命名路由方式 { path: '/c', redirect: to => { //動態返回重定向目標 // 方法接收 目標路由 作為參數 // return 重定向的 字符串路徑/路徑對象 }} ]})const router = new VueRouter({ routes: [ { path: '/a', component: A, alias: '/b' } //別名:當訪問 /b 時也會使用A組件 ]})
新聞熱點
疑難解答
圖片精選