Vue 之导航守卫检查用户是否登陆

34次阅读

共计 829 个字符,预计需要花费 3 分钟才能阅读完成。

导航守卫可以看做是 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>

正文完
 0