index.js
import VueRouter from "vue-router"; import UserSettings from "./UserSettings"; import UserEmailsSubscriptions from "./UserEmailsSubscriptions"; import UserProfile from "./UserProfile"; import UserProfilePreview from "./UserProfilePreview"; function dynamicPropsFn(route) { const now = new Date() return { name: (now.getFullYear() + parseInt(route.params.years)) + '!' } } const routes = [ { path: '/user/settings/:years', props: dynamicPropsFn, // You could also have named views at tho top component: UserSettings, beforeEnter: (to, from, next) => { console.log('beforeEnter'); next(); }, children: [ { path: 'emails', name: 'emails', //redirect: {name: 'profile'}, // redirect: function (to) { // console.log(to); // return {name: 'profile'}; // }, component: UserEmailsSubscriptions, }, { path: 'profile', name: 'profile', //此路由對應包含了兩個Vue視圖組件 components: { default: UserProfile, helper: UserProfilePreview }, }] } ]; const router = new VueRouter({ mode: 'history', routes, }); let isAuthenticated = false; let csrf_token = document.getElementsByName('csrf-token')[0].content; if (csrf_token) { isAuthenticated = true; } else { isAuthenticated = false; } router.beforeEach((to, from, next) => { console.log(csrf_token); console.log('beforeEach'); // console.log(to.name); // console.log(from.name); if (to.name !== 'Login' && !isAuthenticated) { next({name: 'Login'}); } else { next(); } }); router.beforeResolve((to, from) => { console.log('beforeResolve'); // console.log(to.name); // console.log(from.name); }); router.afterEach((to, from) => { console.log('afterEach'); // console.log(to.name); // console.log(from.name); }) export default router;
UserSettings.vue:
<template> <div class="us"> <h2>User Settings {{this.name}}</h2> <UserSettingsNav/> <router-view class="us__content"/> <router-view name="helper" class="us__content us__content--helper"/> </div> </template> <script> import UserSettingsNav from "./UserSettingsNav"; export default { name: "UserSettings", props: ['name'], components: { UserSettingsNav, }, beforeRouteEnter(to, from, next) { console.log('beforeRouteEnter'); // console.log(to.name); // console.log(from.name); next(vm => { }); }, beforeRouteUpdate(to, from, next) { console.log('beforeRouteUpdate'); // console.log(to.name); // console.log(from.name); next(); }, beforeRouteLeave(to, from, next) { console.log('beforeRouteLeave'); // console.log(to.name); // console.log(from.name); next(); }, } </script> <style scoped> </style>
- 导航被触发。
- 在失活的组件里调用离开守卫。
- 调用全局的
beforeEach
守卫。 - 在重用的组件里调用
beforeRouteUpdate
守卫 (2.2+)。 - 在路由配置里调用
beforeEnter
。 - 解析异步路由组件。
- 在被激活的组件里调用
beforeRouteEnter
。 - 调用全局的
beforeResolve
守卫 (2.5+)。 - 导航被确认。
- 调用全局的
afterEach
钩子。 - 触发 DOM 更新。
- 用创建好的实例调用
beforeRouteEnter
守卫中传给next
的回调函数。