Vue 之导航守卫
导航守卫可以看做是 vue-router 的生命周期钩子
如果用户未登陆就前往发帖页面,如何用户重定向到登陆页面?
思路
使用 beforeEach
在页面跳转前对用户的登陆状态进行检查
<!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>
相关推荐
bowean 2020-07-05
yuzhu 2020-11-16
85477104 2020-11-17
KANSYOUKYOU 2020-11-16
sjcheck 2020-11-03
怪我瞎 2020-10-28
源码zanqunet 2020-10-28
gloria0 2020-10-26
王军强 2020-10-21
学习web前端 2020-09-28
QiaoranC 2020-09-25
anchongnanzi 2020-09-21
安卓猴 2020-09-12
Macuroon 2020-09-11
kiven 2020-09-11
LittleCoder 2020-09-11
Cheetahcubs 2020-09-13
小焊猪web前端 2020-09-10