addRouter 使用 , 后台生成路由数据

// 后台生成数据格式
{
    "code": 0,
    "message": "success",
    "menus": [{
            "id": "1",
            "name": "myinfo",
            "path": "/myinfo",
            "component": "views/myinfo/index.vue",
            "meta": {
                "title": "个人中心"
            }
        },
        {
            "id": "2",
            "name": "farm",
            "path": "/farm",
            "component": "views/farm/index.vue",
            "meta": {
                "title": "农场"
            },
            "children": [{
                    "id": "7",
                    "name": "land",
                    "path": "/farm/land",
                    "component": "views/farm/land/index.vue",
                    "meta": {
                        "title": "土地"
                    }
                },
            ]
        },
        {
            "id": "3",
            "name": "person",
            "path": "/person",
            "component": "views/person/index.vue",
            "meta": {
                "title": "人员"
            }
        },
    ]
}
// utils 创建 _import.js
// 用来转化路径
module.exports = file => () => {
  return import('@/' + file)
}

// utils 创建 asyncRouter.js
// 递归 修改后台传回来的  component中的数据 
const _import = require('./_import') // 获取组件的方法
export const asyncRouterHandle = asyncRouter => {
  asyncRouter.map(item => {
    if (item.component) {
      item.component = _import(item.component)
    } else {
      // eslint-disable-next-line dot-notation
      delete item['component']
    }
    if (item.children) {
      asyncRouterHandle(item.children)
    }
  })
  console.log('asyncRouter', asyncRouter)
}
// router.js

// 获取原型对象上的push函数
const originalPush = Router.prototype.push
// 修改原型对象中的push方法
Router.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const baseRouters = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index')
  }
  // {
  //   path: '/layout',
  //   name: 'layout',
  //   component: () => import('@/views/layout/index.vue')
  // }
]

// 需要通过后台数据来生成的组件

const createRouter = () =>
  new Router({
    routes: baseRouters
  })

const router = createRouter()

export default router


// stoure  router.js 调用接口 获取路由数据  
import { asyncRouterHandle } from '@/utils/asyncRouter'

import { login } from '@/api/login'
const routerList = []
const formatRouter = routes => {
  routes &&
    routes.map(item => {
      if (
        (!item.children || item.children.every(ch => ch.hidden)) &&
        item.name !== '404'
      ) {
        routerList.push({ label: item.meta.title, value: item.name })
      }
      if (item.children && item.children.length > 0) {
        formatRouter(item.children)
      }
    })
}

export const router = {
  namespaced: true,
  state: {
    asyncRouters: [],
    routerList: routerList
  },
  mutations: {
    setRouterList (state, routerList) {
      state.routerList = routerList
    },
    // 设置动态路由
    setAsyncRouter (state, asyncRouters) {
      state.asyncRouters = asyncRouters
    }
  },
  actions: {
    // 从后台获取动态路由
    async SetAsyncRouter ({ commit }) {
      const baseRouter = [
        {
          path: '/layout',
          name: 'layout',
          component: 'views/layout/index.vue',
          meta: {
            title: '底层layout'
          },
          children: []
        }
      ]
      const asyncRouterRes = await login()  // 本地json 数据 , 放在 publick中 ,只能用get 请求
      const asyncRouter = asyncRouterRes.data && asyncRouterRes.data.menus
      asyncRouter.push({
        path: '404',
        name: '404',
        hidden: true,
        meta: {
          title: '迷路了*。*'
        },
        component: 'view/error/index.vue'
      })
      formatRouter(asyncRouter)
      baseRouter[0].children = asyncRouter

      baseRouter.push({
        path: '*',
        redirect: '/layout/404'
      })
      asyncRouterHandle(baseRouter)
      commit('setAsyncRouter', baseRouter)
      commit('setRouterList', routerList)
      return true
    }
  },
  getters: {
    // 获取动态路由
    asyncRouters (state) {
      return state.asyncRouters
    },
    routerList (state) {
      return state.routerList
    },
    defaultRouter (state) {
      return state.defaultRouter
    }
  }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值