Vue 路由守衛
router.beforeEach: 全局前置路由守衛,每次切換之前被調用,可以做權限攔截
router.afterEach: 全局后置路由守衛,每次切換之后調用, 可用於切換document.title
router.beforeEnter: 獨享路由守衛,只有前置,沒有后置,寫在routes配置項里
router.beforeRouteEnter: 組件內路由守衛, 寫在組件中,路過路由規則進入該組件時被調用
router.beforeRouteLeave: 組件內路由守衛, 寫在組件中,路過路由規則離開該組件時被調用
全局前置路由守衛
router.beforeEach((to,from,next)=>{})
每次前置路由守衛都要調next方法,否則無法繼續
全局后置守衛
router.afterEach((to,from)=>{})
獨享路由守衛
router.beforeEnter((to,from,next)=>{})
組件內路由守衛
router.beforeRouteEnter((to,from,next)=>{}): 組件內路由守衛, 寫在組件中,路過路由規則進入該組件時被調用
router.beforeRouteLeave((to,from,next)=>{}): 組件內路由守衛, 寫在組件中,路過路由規則離開該組件時被調用
案例
main.js
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import router from './router'
// 關閉Vue的生產提示
Vue.config.productionTip = false
Vue.use(VueRouter)
// 全局路由前置守衛
router.beforeEach((to,from,next)=>{
console.log('beforeEach',to,from)
next()
})
// 全局路由后置守衛
router.afterEach((to,from)=>{
console.log('afterEach',to,from);
})
// 創建Vue實例
new Vue({
// 將app組件放入容器中
render: h => h(App),
router
}).$mount('#app')
router/index.js
import VueRouter from 'vue-router'
import Island from '../pages/Island'
import Polaris from '../pages/Polaris'
export default new VueRouter({
routes: [
{
component: Island,
path: "/Island",
props: ($routes) => ({
id: $routes.query.id,
title: $routes.query.title
})
},
{
component: Polaris,
path: "/Polaris",
// 組件獨享路由守衛
beforeEnter:(to,from,next)=>{
next()
}
},
]
})
island.vue
<template>
<h1>
message by Island
{{ id }}
-
{{ title }}
</h1>
</template>
<script>
export default {
props: ["id", "title"],
name: "Island",
created() {
console.log("Isalnd 創建");
},
beforeDestroy() {
console.log("Isalnd 即將被銷毀");
},
activated() {
console.log("Island 激活...");
},
deactivated() {
console.log("Island 失活...");
},
// 組件路由前置守衛
beforeRouteEnter(to, from, next) {
console.log("beforeRouteEnter", arguments);
next();
},
// 組件路由后置守衛
beforeRouteLeave(to, from, next) {
console.log("beforeRouteLeave", arguments);
next();
},
};
</script>
<style scoped>
h1 {
color: salmon;
}
</style>