導航守衛能夠看作是 vue-router 的生命週期鉤子html
若是用戶未登錄就前往發帖頁面,如何用戶重定向到登錄頁面?vue
思路
使用 beforeEach
在頁面跳轉前對用戶的登錄狀態進行檢查vue-router
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="https://unpkg.com/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> </head> <body> <div id="app"> <h1>Hello App!</h1> <p> <router-link to="/login">Go to login</router-link> <router-link to="/post">Go to post</router-link> </p> <router-view></router-view> </div> </body> <script> const login = { template: '<div>login</div>' } const post = { template: '<div>post</div>' } const routes = [ { path: '/login', component: login }, { path: '/post', component: post } ] const router = new VueRouter({ routes: routes }) router.beforeEach(function (to, from, next) { let login = false if (!login && to.path == '/post') { next('/login') } else { next() } }) const app = new Vue({ router }).$mount('#app') </script> </html>