18.VUE_路由_name的用法

本文详细介绍了Vue路由中name属性的三种用法:1) 为不同router-view指定渲染组件;2) 通过name传参获取组件name值;3) 在params传参中作为引入参数。理解name属性对于优化Vue应用的路由管理至关重要。
摘要由CSDN通过智能技术生成
在这里插入代码片

我们在定义每个路由的时候会有一个name的属性(如下面代码),通常我们不定义这个属性发现也没有任何问题,那么这个name到底有什么用呢?

export default new Router({
   
  mode: 'history',
  routes: [
    {
   
      path: '/',
      name: 'Hello',
      component: Hello
    }, {
   
      path: '/text',
      name: 'text',
      component: text
    
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这是一个非常不错的自动化路由生成的方法,使用 `require.context` 可以快速地遍历 views 文件夹下的所有 .vue 文件。下面是一个示例代码: ```javascript import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) // 生成路由配置 function generateRoutes(routeContext) { const routes = [] // 遍历所有 .vue 文件 routeContext.keys().forEach(key => { // 获取文件相对路径,如 './User.vue' const routePath = key.replace(/^\.\/(.*)\.\w+$/, '$1') // 根据文件路径生成路由配置 const routeConfig = { path: `/${routePath}`, name: routePath, component: () => import(`@/views/${routePath}.vue`) } // 判断是否是一级路由 if (routePath === 'Login' || routePath === 'Home') { routes.push(routeConfig) } else { const [parentPath, childPath] = routePath.split('/') let parentRoute = routes.find(route => route.path === `/${parentPath}`) if (!parentRoute) { parentRoute = { path: `/${parentPath}`, component: () => import(`@/views/${parentPath}/index.vue`), children: [] } routes.push(parentRoute) } parentRoute.children.push(routeConfig) } }) return routes } // 使用 require.context 生成路由配置 const routeContext = require.context('@/views', true, /\.vue$/) const routes = generateRoutes(routeContext) // 创建路由实例 const router = new Router({ mode: 'history', routes }) export default router ``` 在上面的代码中,我们首先定义了 `generateRoutes` 函数,它接受一个 `require.context` 对象作为参数,遍历所有 .vue 文件,根据文件路径生成路由配置。根据要求,Login.vue 和 Home.vue 固定在 views 下作为一级路由,其他和 Login.vue 同一目录下的 vue 文件也是一级路由,其他文件夹下的 vue 文件以 index.vue 作为出口,且文件夹下的 index.vue 均在 Home.vue 的 children 下,其他文件夹下的除 index.vue 文件的路由均在 index.vue 的 children 下。 然后,我们使用 `require.context` 生成路由配置,并调用 `generateRoutes` 函数生成路由配置数组。最后,我们使用 `new Router` 创建路由实例,并将路由配置数组作为参数传入。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值