如何动态更改VueRouter源文件?

时间:2019-10-03 07:31:12

标签: javascript laravel vue.js vuejs2 vue-router

你好,我有一个包含多个角色的项目(VueJs + Laravel),我使用laravel作为后端,使用vuejs作为前端, 我有三个不同的角色(用户,编辑器,编辑器)。

这是我在app.js中的代码

// VueRouter
import VueRouter from 'vue-router';
import routes from './routes.js';
Vue.use(VueRouter);

var router = new VueRouter({
    mode: 'history',
    routes
})

这是我的路线文件:

let routes = [

    // General 
    { path: '/about', component: require('./components/Home/About.vue').default },
    { path: '/pasword-change',  component: require('./components/ChangePassword.vue').default },

    // User
    { path: '/User', component: require('./components/User/Dashboard.vue').default },


    // Modirator
    { path: '/Modirator', component: require('./components/Modirator/Dashboard.vue').default },

    // Editor
    { path: '/Editor', component: require('./components/Editor/Dashboard.vue').default },


    // Error
    { path: '*', component: require('./components/Errors/404.vue').default} },

]
export default routes

登录后,如果角色是用户使用(routes-user.js),我想在后端作为ajax请求对其进行检查;否则,如果角色是修改者使用(routes-mod.js),否则是(routes.js)。

我不想在客户端中显示 / user / modirator / editor ,但是我想在登录后检查并且每个角色都显示根网址 / 中的组件。 感谢您的帮助。

感谢帮助。...

2 个答案:

答案 0 :(得分:1)

我测试了一些与您对Vuex中正常组件传递和延迟加载组件的要求类似的方法,并且可以正常工作。下面是我要执行的代码,其中包含一个“未授权”变量,并基于该变量使用javascript三元运算符或javascript模板字符串加载其他组件。

import Vue from 'vue'
import Router from 'vue-router'
import Auth from './views/Auth.vue'
import Board from './views/Board.vue'

Vue.use(Router)

let unauthorized = true;

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/auth',
      name: 'authenticate',
      component: unauthorized ? Auth : Board
    },
    {
      path: '/',
      name: 'home',
      component: () => import(`./views/${unauthorized ? 'Auth.vue': 'Board.vue'}`)
    }
  ]
})

特定解决方案

根据您的要求,您可以根据是以“主持人”,“用户”还是“编辑者”身份登录然后在router.js文件中获取变量,将变量(“访问类型”)存储在本地存储中并使用模板字符串功能有条件地更改组件路径。

如果需要更多帮助,请告诉我。

答案 1 :(得分:0)

您可以在路线中添加元数据以解决问题,并在输入路线之前检查元数据:

object Form1: TForm1
  Left = 210
  Top = 181
  Width = 544
  Height = 375
  Caption = 'Form1'
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'MS Sans Serif'
  Font.Style = []
  OldCreateOrder = False
  OnCreate = FormCreate
  PixelsPerInch = 96
  TextHeight = 13
end

然后将以下方法添加到路由器:

    { path: '/about', component: require('./components/Home/About.vue').default },
    { path: '/pasword-change',  component: require('./components/ChangePassword.vue').default },

    // User
    { path: '/User', component: require('./components/User/Dashboard.vue').default, meta: {authorize: ["Admin"]} },