Vue-router:11、addRoutes动态路由添加
在前面的案例中,我们都是将路由定义好,然后通过路由守卫来判断,某个用户是否登录,从而决定能否访问某个路由规则对应的组件内容。
但是,如果某些路由规则只能用户登录以后才能够访问,那么我们也可以不用提前定义好,而是在登录后,通过addRoutes
方法为其动态的添加。
首先这里需要,还需要全局的路由守卫来进行校验判断,只不过这里全局路由守卫的逻辑发生了变化。
router.beforeEach((to, from, next) => {
//to:去哪个页面,from来自哪个页面,next继续执行.
if (window.isLogin) {
//用户已经登录
if (to.path === "/login") {
// 用户已经登录了,但是又访问登录页面,这里直接跳转到用户列表页面
next("/");
} else {
//用户已经登录,并且访问其它页面,则运行访问
next();
}
} else {
//用户没有登录,并且访问的就是登录页,则运行访问登录页
if (to.path === "/login") {
next();
} else {
//用户没有登录,访问其它页面,则跳转到登录页面。
next("/login?redirect=" + to.fullPath);
}
}
});
下面对登录组件进行修改
const Login = {
data() {
return {
isLogin: window.isLogin,
};
},
template: `<div>
<button @click="login" v-if="!isLogin">登录</button>
<button @click="logout" v-else>注销</button>
</div>`,
methods: {
login() {
window.isLogin = true;
if (this.$route.query.redirect) {
//动态添加路由:
this.$router.addRoutes([
{
path: "/",
component: App,
redirect: "/users",
children: [
{
path: "/users",
component: Users,
meta: {
auth: true,
},
// beforeEnter(to, from, next) {
// if (window.isLogin) {
// next();
// } else {
// next("/login?redirect=" + to.fullPath);
// }
// },
},
{
path: "/userinfo/:id", component: UserInfo, props: true },
{
path: "/rights", component: Rights },
{
path: "/goods", component: Goods },
{
path: "/orders", component: Orders },
{
path: "/settings", component: Settings },
],
},
]);
this.$router.push(this.$route.query.redirect);
}