其他分享
首页 > 其他分享> > vueAdmin动态路由

vueAdmin动态路由

作者:互联网

1.把后台返回的数据整理成vue路由需要的格式

const datarouter = {
  state: {
    asyncRoutes: {}, // 动态路由, 最终要通过路由的addRoutes挂上去
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      buildRouter(routers)
      formatRouter(routers)
      state.asyncRoutes = routers
    }
  },
  actions: {
    generateRoutes({
      commit
    }, data) {
      commit('SET_ROUTERS', data)
    }
  }
}

function buildRouter(rs) {
  for (let i = 0; i < rs.length; i++) {
    var r = rs[i]
    try {
      delete r.url
      delete r.sortNum
      delete r.type
      delete r.parentId
      const rr = JSON.parse(r.router)
      r.path = rr.path
      r.component = rr.component

      r.meta = {title: '', icon: ''}
      r.meta.title = r.name
      r.meta.icon = rr.icon
      delete r.name
      delete r.router
    } catch (e) {
      console.error(e)
    }
    if (r.children && r.children.length) {
      buildRouter(r.children)
    }
  }
}

/**
 * 将component转为function
 */
function formatRouter(routers) {
  for (let i = 0; i < routers.length; i++) {
    const route = routers[i]
    // route.component = () => import('@/views/' + route.component)
    route.component = loadView(route.component)
    if (route.children && route.children.length) {
      formatRouter(route.children)
    }
  }
}
/**
 * 懒加载
 */
function loadView (view) {
  if(view === 'Layout') {
    return resolve => require(['@/layout/index'], resolve)
  }
  return resolve => require([`@/views/${view}`], resolve)
}
export default datarouter

2.生成路由后,还需要做件事:a把路由add进路由,b,在左边菜单栏显示:

 // 生成路由
            this.$store.dispatch('generateRoutes', res.data.routers).then(()=> {
              this.$router.addRoutes(this.$store.state.datarouter.asyncRoutes)
              this.$router.push({ path: this.redirect || '/' })
              this.loading = false
            })

并把layout/components/Sidebar/index中把routes方法改为:

routes() {   return this.$router.options.routes.concat(this.$store.state.datarouter.asyncRoutes) }         --------------------------------个人纪录,我个人做笔记而已,读者不用看了------------------------------- -----------------小知识---------------- 1.请求中的url支持正则如:url: '/article/[A-Za-z0-9]/comments', 2.vuex持久化插件,防止页面刷新vuex清空:     ①npm install vuex-persistedstate  --save     ②new Vuex.Store中添加plugins[createPersistedState({storage: window.sessionStorage})], 需要引包import createPersistedState from "vuex-persistedstate" -----------------个人经验----------------- 1.移除main.js中的 if (process.env.NODE_ENV === 'production') {   const { mockXHR } = require('../mock')   mockXHR() } 2.util中auth.js需要为每个项目知名TokenKey,防止冲突 3.项目中一个从js中获取token,一个从vuex中获取,不知道为什么这样设计,自己约定  -->  "重置"使用: await store.dispatch('user/resetToken'),  -->  "添加"使用: await.store.commit('SET_TOKEN', response.data) 因为我把cookie设置x-token和vuex里设置x-token都放SET_TOKEN了. 4.我的返回的信息是msg,源文件是message,要改; 同时后台返回的头部需要指定"Access-Control-Allow-Headers", "x-requested-with,content-type,X-Token" 5.request.js中withCredentials要设为true,携带cookie后才能允许后端session,  但是后端Access-Control-Allow-Origin不能设为*,必须指明http://ip+端口了 6.源文件user.js里的login方法需要resolve(response)把response返回过来 7.个人约定-999表示需要重新登陆 8.动态路由,添加dtarouter.js,然后再登陆页面的登陆方法then加入: this.$store.dispatch('generateRoutes', res.data.routers).then(()=> {   this.$router.addRoutes(this.$store.state.datarouter.asyncRoutes)   this.$router.push({ path: this.redirect || '/' })   this.loading = false }) 然后还要把layout/components/Sidebar/index中把routes方法改为: routes() {   return this.$router.options.routes.concat(this.$store.state.datarouter.asyncRoutes) },
一. .env.developtntw文件: 1.改端口在.env.developtnt中改,注意需要大写 2.设置请求地址前缀:VUE_APP_BASE_API

标签:vueAdmin,routers,route,state,store,router,动态,路由
来源: https://www.cnblogs.com/trump2/p/13703386.html