index.jsimport VueRouter from "vue-router";import UserSettings from "./UserSettings";import UserEmailsSubscriptions from "./UserEmailsSubscriptions";i... ...
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
的回調函數。