vue中路由守卫的理解
在实际项目中,路由跳转前做一些验证,比如登录验证,是网站中的普遍需求。举个例子,我们通常使用 router.beforeEach 注册一个全局前置守卫用来判断登录的状态:
let routesArr = [{
path: '/home',
name:"home",
//redirect:"/about",//重定向
//alias: '/index',//别名
component: {
template: `<div>
<h1>这是首页</h1>
</div>`
}
}, {
path: '/about',
name:'about',
component: {
template: `<div>
<p>这是关于我们页</p>
</div>`
}
}, {
path: '/user/:name', // :name的作用是动态访问一个地址,比如传进来的是张三,就显示张三的信息
name: 'user', // 这个name的作用是配合第95行添加属性用的,二者必须一致
component: {
template: `<div>
<!-- $route.params的作用是接收传进来的名字,例如传张三 name就是张三 -->
<p>我叫:{{ $route.params.name }}</p>
<!-- $route.query的作用是接收url上 ?age=18 这样的参数 例如 router.html#/user/张三?age=18 -->
<p>我今年:{{ $route.query.age }} 岁了</p>
<div>
<!-- append是为了给下面的children子路由传数据 -->
<router-link to="more" append> 更多信息 </router-link>
</div>
<!-- 这个router-view对应的就是children里的template -->
<router-view></router-view>
</div>`
},
children: [{
path: 'more',
component: {
template: `
<div>
用户:{{ $route.params.name }} 的详细信息 abcd1234
</div>`
}
}]
}
];
const vRouter = new VueRouter({
routes: routesArr // 这里要写routes ,而不是routers,不然 <router-view> 没数据
})
vRouter.beforeEach((to, from, next) => {
//这里写你的判断逻辑
const nextRoute = ['home', 'good-list', 'good-detail', 'cart', 'profile'];//需要登陆的页面名
let isLogin= localEvent.get('web_login')||false;//获取是否登录状态
// 未登录状态;当路由到nextRoute指定页时,跳转至login
if (nextRoute.indexOf(to.name) > -1) {
if (!isLogin) {
//router.push({ name: 'login' });//可以直接跳转名
//next({ path: '/login', query: { redirect: to.fullPath } });//也可以跳转路径,并带上重定向
}
}
// 已登录状态;当路由到login时,跳转至home
if (to.name === 'login') {
if (isLogin) {
router.push({ name: 'home' });
}
}
next();
});

浙公网安备 33010602011771号