路由守卫的应用
组件导航的巧用
- 除了应用于导航栏外,组件导航还可应用用去往详情页:
<template>
<el-row class="menu-card" type="flex" justify="start">
<el-col
v-for="item in info"
:key="item._id"
style="flex: none"
:style="{ 'margin-left': marginLeft + 'px' }"
>
<el-card :body-style="{ padding: '0px' }">
<router-link :to="{ name: 'detail', query: { menuId: item._id } }">
<img
:src="item.product_pic_url"
class="image"
style="width: 232px; height: 232px"
/>
<div style="padding: 14px" class="menu-card-detail">
<strong>{{ item.title }}</strong>
<span>{{ item.comments_len }} 评论</span>
<router-link
:to="{ name: 'space', query: { userId: item.userId } }"
tag="em"
>
{{ item.name }}
</router-link>
</div>
</router-link>
</el-card>
</el-col>
</el-row>
</template>
由于a标签内不能再写a标签,因此router-link里边的router-link加上tag=“em”,意为渲染成em标签
组件内的守卫的应用
- 比如在别的页面在离开当前页面之前,需要一些操作
beforeRouteLeave(to, from, next) {
if(to.name === "business_create") {
......
}
} else{
next();
},
beforeRouteUpdate
、beforeRouteEnter
用法相同
全局守卫的应用
- 最常见的应用于页面鉴权登录
router.beforeEach(async (to, from, next) => {
const token = localStorage.getItem("token");
const isLogin = !!token;
// 进入路由的时候,都要想后端发送token,验证合法不合法
// 不管路由需要不需要登录,都需要展示用户信息
// 都需要向后端发请求,拿到用户信息
const data = await userInfo();
Store.commit("chnageUserInfo", data.data);
// 判断哪些页面需要登录
if (to.matched.some((item) => item.meta.login)) {
// 需要登录,判断登录状态
if (isLogin) {
if (data.error === 400) {
// 后端告诉你,登录没成功
next({ name: "login" });
localStorage.removeItem("token");
return;
}
if (to.name === "login") {
next({ name: "home" });
} else {
next();
}
return;
}
// 没登录,进入login,直接进入
if (!isLogin && to.name === "login") {
next();
}
// 没登录,进入的不是login,跳到login
if (!isLogin && to.name !== "login") {
next({ name: "login" });
}
} else {
next();
}
});
路由独享守卫的应用
const router = new VueRouter({
routes: [
{
path: "/foo",
component: Foo,
beforeEnter: (to, from, next) => {
// ...
},
},
],
});