vue 自动生成路由,path和name默认去除index

在这里插入图片描述
router.js

/**
 * 规则:
 * 一、例如:index/index,shop/index以index结尾的,path和name默认去除index
 * 二、例如:shop/list,默认生成name为shop_list(如果结尾为index,例如shop/index则是shop)
 * 三、填写后不会自动生成
 * **/
let routes = [{
    redirect: {
      name: 'index'
    },
    // component: () => import('../../views/layout.vue'),
    component: 'layout',
    children: [{
        component: 'index/index',
        meta: {
          title: '后台首页'
        }
      },
      {
        component: 'shop/goods/list',
        meta: {
          title: '商品列表'
        }
      },
      {
        component: 'isimage/index',
        meta: {
          title: '相册管理'
        }
      },
      {
        component: 'shop/category/list',
        meta: {
          title: '分类列表'
        }
      },

    ]
  },
  {
    component: 'login/index',
    meta: {
      title: '登录页'
    }
  },
  {
    path: '*',
    redirect: {
      name: 'index'
    }
  }
]
// 获取路由信息方法
let getRoutes = function () {
  // 生成路由详细信息
  createRoute(routes)
  return routes
}
// 自动生成路由
function createRoute(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (!arr[i].component) return
    // 去除index
    let val = getValue(arr[i].component)
    // 生成name
    arr[i].name = arr[i].name || val.replace(/\//g, '_')
    // 生成path
    arr[i].path = arr[i].path || `/${val}`
    // 自动生成component
    let componentFun = import(`../../views/${arr[i].component}.vue`)
    arr[i].component = () => componentFun
    if (arr[i].children && arr[i].children.length > 0) {
      createRoute(arr[i].children)
    }
  }
}

// 去除index
function getValue(str) {
  // str = login/index
  // 获取最后一个/的索引
  let index = str.lastIndexOf('/')
  // 获取最后一个/后面的值
  let val = str.substring(index + 1, str.length)
  // 判断是不是index结尾
  if (val === 'index') {
    return str.substring(index, -1)
  }
  return str
}
export default getRoutes()

在这里插入图片描述

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import routes from "@/common/config/router.js"
export default new VueRouter({
  routes
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值