目标:
点击个人中心,判断是否登录,如果登录就跳转到个人中心,没有登录就跳转到登录界面
- 创建两个页面
创建两个页面,分别是个人中心和登录界面
- 在仓库写个标志记录是否登录
import { createStore } from 'vuex';
export default createStore({
state: {
user: {
isLogin:false, //是否登录
}
}
})
- 在个人中心路由中加入导航守卫
根据自己需要,实现跳转页面
<span class="navBtn" @click="$router.push('/personal')">我的</span>
在路由文件中编写导航守卫
{
path: '/personal',
name: 'MyView',
beforeEnter: (to, from, next) => {
if (store.state.user.isLogin) {
next() // 如果登录了就跳转到
} else {
next('/login') // 如果没登陆跳转到登录界面
}
},
component: () => import('@/views/MyView.vue'),
},
{
path: '/login',
name: 'Login',
component: () => import('@/views/Login.vue'),
},
实现效果
当第二步的isLogin为false时
点击我的之后发现跳转到login页面
当第二步的isLogin为true时
点击我的之后发现跳转到personal页面