vue-router 设置权限时动态加载路由

动态加载路由有几种方案

  1. 前端自己根据不同的用户设置对应的路由表
  2. 后端哥哥们给设置好路由表,前端请求接口拿到路由表

本文采用的是第一种方法

大概的思路:

  1. 设置不同的路由表
  2. 将用户注册的一部分信息存储到vux
  3. 根据用户的不同身份 在跟组件created时以及登陆请求成功时,都将不同的路由表添加到当前路由表中;;第一种是为了防止用户点击刷新而造成路由初始化;;第二种就是登陆成功后立马准备好对应的路由表

注: 404路由写在动态路由中,否则可能会有闪屏和路由为空时加载的404页面(没有亲测,看其他人说的)

1.设置路由表

//管理者路由
export const ManagerRouter = [
  {
    path: "/index",
    component: Index,
    children: [
      {
        path: "/infolist",
        name: "InfoList",
        component: InfoList
      },
      {
        path: "/fundlist",
        name: "FundLst",
        component: FundList
      }
    ]
  },
  
];
//公共路由
const PublicRouter = [
  {
    path: "/index",
    component: Index,
    children: [
      {
        path: "",
        component: Home
      },
      {
        path: "/home",
        name: "Home",
        component: Home
      }
    ]
  },
  {
    path: "/register",
    name: "Register",
    component: Register
  },
  {
    path: "/login",
    name: "Login",
    component: Login
  },
  {
    path: "*",
    name: "NotFound",
    component: NotFound
  }
];

2.vuex保存用户信息
3.根据用户权限,添加对应路由表(首先是APP根组件使用this.$router.addRoutes(newRoutes)

···省略其他代码
 created(){
            // 解决刷新后状态初始化
            if(sessionStorage.eleToken){
                //解析token
                const decode = jwt_decode(sessionStorage.eleToken);
                //动态渲染路由
                if(decode.identity == 'manager'){
                    this.$router.addRoutes(ManagerRouter);
                }
                //把解析的token存的vuex中
                this.$store.dispatch('setAuthenticated',!this.isEmpty(decode));
                this.$store.dispatch('setUser',decode);
            }
        },

4.登陆组件根据用户信息添加路由表

 submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.$axios.post('/login',this.loginUser)
                            .then(res=>{
                                // console.log(res);
                                //存储Token
                                const {token} = res.data;
                                sessionStorage.setItem("eleToken",token);
                                //解析token
                                const decode = jwt_decode(token);
                                //动态渲染路由
                                if(decode.identity == 'manager'){
                                    this.$router.addRoutes(ManagerRouter);
                                }
                                //把解析的token存的vuex中
                                this.$store.dispatch('setAuthenticated',!this.isEmpty(decode));
                                this.$store.dispatch('setUser',decode);
                                //跳转到首页
                                this.$router.push('/index');
                            })
                    } 
                });
            },

参考文章:vue-router的路由权限控制

你可能感兴趣的:(vue)