vue add router
使用歷史模式嗎?Y
項目中生成router.js文件,所以在main.js主入口文件中引入import router from './router.js'
在new Vue({router: router})
中使用
routes:[]
中component:() => import('./views/Home.vue');
懶加載
routes:[]
中redirect: () => { console.log(to.path) }
重定向導航
routes:[]
中path: '*'
以上所有導航不匹配時的其餘路徑
導航選中class類名router-link-exact-active router-link-active
this.$router.push('/home');
js控制導航到某個位置
this.$route
返回當前頁面導航信息參數,如params
、path
動態路由:
-
<router-link :to="{name: 'question', params: {id: ...}}"></router-link>
必須使用name屬性,使用path屬性不起作用 -
this.$router.push({ name: 'question',params: {id:...} })
設置跳轉路由路徑,一般更新了路徑頁面不跳轉,需要配合路由生命週期函數使用 =>beforeRouteUpdate(){}
路由路徑更新時執行
組件路由守衛
-
beforeRouteLeave(to,from,next){ next() }
路由生命週期函數,在路由離開之前執行,next執行纔會切換 -
beforeRouteEnter(to,from,next) {}
路由生命週期函數,到達當前路由執行,next需要執行才能到達,並且函數內部不能獲取組件實例this,如果需要獲取組件實例,需要在next中獲取next((vm) => { console.log(vm) })
-
beforeRouteUpdate(to,from,next){}
路由路徑更新時執行
路由獨享守衛
-
routes: [ {..., beforeEnter(to,from,next){} } ]
寫在router.js中某個路徑下獨享的守衛
全局路由守衛
-
router.beforeEach((to,from,next) => { next(); })
全局路由變化時守衛,main.js全局中定義 -
router.beforeResolve(to,from,next){}
所有組件解析完成之前執行 -
router.afterEach(){}
所有組件解析完成之後執行,沒有參數
路由守衛執行順序:全局守衛beforeEach => 路由獨享守衛 => 組件路由守衛 => 全局守衛beforeResolve => 全局守衛afterEach
路由元信息:routes:[{..., meta:{login: true} }]
- 通過meta來判斷不太準確,因爲如果使用了重定向,那麼子路由就沒有meta信息。但是可以通過
this.$route.matched[0].meta
或者導航守衛函數參數to.matched[0].meta
獲取
通過路由元信息跳轉登錄
//main.js
router.beforeEach((to,from,next)=>{
const needLogin = to.matched.some(item.meta && item.meta.login);
if(needLogin) {
const isLogin = document.cookie.includes('login=true');
if(isLogin) {
next();
}else {
const toLoginFlag = window.confirm('該頁面需要登錄才能訪問,需要去登錄嘛?')
if(toLoginFlag) {
next('/login');
}
}
}else {
next();
}
})