Vue-router:11、addRoutes动态路由添加

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);
            } 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值