记录!Nuxt配置路由meta的简单方法

2,598 阅读1分钟

有问题一定要看官方文档啊!

背景

需求是做个调试页,在一个单页面中获取所有页面的路由参数,想在路由的meta里设title,用于设页面别名

踩过的坑:

引入过nuxt-route-meta,新项目引入没有问题,我这个项目引入就报错,且这个插件只支持meta,没有支持其他的路由参数,就跳过。

官方文档

翻到官方文档里有这么三种扩展方式: image.png

首先排除第二和第三个

  1. 第二种方式:我想保留预定式路由,就跳过
  2. 第三种方式:
    • extendRoutes方式,引入外部js文件会导致ui插件引入异常,原因未知
    • 写法不优雅,需要单独页面维护
    • 懒加载写法支持困难,就跳过

故选第一个插件:@nuxtjs/router-extras

  • 该包扩展了我想要的全部的路由功能
  • 也没有破坏约定式路由
  • 使用简单,只需要在每个vue单文件中配置好页面路由参数即可

image.png

使用步骤

1、安装:

yarn add --dev @nuxtjs/router-extras # or npm install --save-dev @nuxtjs/router-extras

2、nuxt.config.js中配置

如果你的nuxt版本低于2.9.0,就这么设置:

{
  buildModules: [
    // Simple usage
    '@nuxtjs/router-extras',

    // With options
    ['@nuxtjs/router-extras', { /* module options */ }]
  ]
}

正常使用:

{
  buildModules: [
    '@nuxtjs/router-extras'
  ],
  routerExtras: {
    /* module options */
  }
}

3、vue单文件中使用

<template>...</template>
<router>
  {
    path: '/user'
    meta: {
      module: '用户模块',
      title: '用户'
    }
  }
</router>

<script>
export defaut {
  created() {
     // 这里就能拿到所有的路由参数啦
    this.routes = this.$router.options.routes;
    console.log('%c [ this.routes ]', 'font-size:13px; background:pink; color:#bf2c9f;', this.routes)
    }
  },
</scipte>

目前唯一的缺憾是,不支持热更新,路由配置修改之后要重新构建才会生效~