Vue 路由导航守卫
1.在路由配置中定义导航守卫:定义两个路由:首页和登录页面。
其中,首页需要登录才能访问,因此我们在路由配置中添加了一个 meta 属性,并设置 requiresAuth 为 true。在导航守卫中,我们判断当前路由是否需要登录,如果需要但未登录,则跳转到登录页面;否则放行。
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import Login from './views/Login.vue'
Vue.use(Router)
const router = new Router({
routes: [
{
path: '/',
name: 'home',
component: Home,
meta: {
requiresAuth: true // 需要登录才能访问的页面
}
},
{
path: '/login',
name: 'login',
component: Login
}
]
})
router.beforeEach((to, from, next) => {
const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
const isAuthenticated = localStorage.getItem('token')
if (requiresAuth && !isAuthenticated) {
next('/login') // 如果需要登录但未登录,则跳转到登录页面
} else {
next() // 否则放行
}
})
export default router
2.在登录页面中,登录成功后保存登录状态信息:
在登录请求成功后,我们将返回的 token 保存到 localStorage 中,表示当前用户已登录。
import axios from 'axios'
export default {
methods: {
login() {
axios.post('/api/login', {
username: this.username,
password: this.password
}).then(res => {
localStorage.setItem('token', res.data.token) // 将登录状态信息保存到 localStorage 中
this.$router.push('/') // 跳转到首页
}).catch(err => {
console.error(err)
})
}
}
}
3.在需要登录才能访问的页面中,判断用户是否已登录:
在 created 生命周期中判断用户是否已登录,如果未登录,则跳转到登录页面。
export default {
created() {
const isAuthenticated = localStorage.getItem('token')
if (!isAuthenticated) {
this.$router.push('/login') // 如果用户未登录,则跳转到登录页面
}
}
}