修订:新的方式使用了 process.cwd()
替代了 __dirname
,能够随意在外部引用自定的 routes
首先,在 nuxt.config.js
中,有 router
属性可配置 ,且 router
可配置对象中有 extendRoutes
扩展路由方法。
1:在根目录下新增 router 文件夹并创建 Index.js 文件。(就像vue中一样)
2:引入 path 模块,并简单封装成resolve方法,这里不要用 __dirname
,否则路由暴露出去调用时 刷新页面会出错,因为刷新时__dirname
是不存在的。
这里要用 process.cwd()
,process.cwd() 会拿到你项目运行时所在的文件目录。
// router/index.js
// 引入path
import path from 'path'
// 要使用 process.cwd()
const resolve = (pagePath) => path.resolve(process.cwd(), `./${pagePath}`)
// 下面这种方式不可取
// const resolve = (pagePath) => path.resolve(__dirname, pagePath)
3:自定义路由相关属性(就像vue中定义的一样)
// router/index.js
// 简单定义一下
export const $routes = [
{
path: '/',
name: 'Home',
component: resolve('pages/home/index.vue'),
meta: {
title: '首页',
icon: 'icon-home'
}
},
{
path: '/dashboard',
component: resolve('pages/dashboard/index.vue'),
meta: {
title: '控制台',
icon: 'icon-dashboard'
},
children: [
{
path: '',
name: 'dashboard-cloud',
component: resolve('pages/dashboard/cloud/index.vue'),
meta: {
title: '云云云',
icon: 'icon-cloud'
}
}
]
}
]
4:定义 extendRoutes 方法,清除原有的nuxt自动生的路由,添加自己的新路由(最重要的一步), routes.length = 0
// router/index.js
const extendRoutes = (routes) => {
routes.length = 0
routes.push(...$routes)
}
5:最后定义router对象并暴露出去,然后直接在 nuxt.config.js中使用即可
// router/index.js
export default { base: '/', extendRoutes }
完整代码附上:
// router/index.js
import path from 'path'
const resolve = (pagePath) => path.resolve(process.cwd(), `./${pagePath}`)
export const $routes = [
{
path: '/',
name: 'Home',
component: resolve('pages/home/index.vue'),
meta: {
title: '首页',
icon: 'icon-home'
}
},
{
path: '/dashboard',
component: resolve('pages/dashboard/index.vue'),
meta: {
title: '控制台',
icon: 'icon-dashboard'
},
children: [
{
path: '',
name: 'dashboard-cloud',
component: resolve('pages/dashboard/cloud/index.vue'),
meta: {
title: '云云云',
icon: 'icon-cloud'
}
}
]
}
]
const extendRoutes = (routes) => {
routes.length = 0 // 清除 nuxt 自己生成的路由,这里不要用 空数组 赋值
routes.push(...$routes)
}
export default { base: '/', extendRoutes }
// nuxt.config.js
import router from './router'
export default {
..., // 其他属性配置
router,
... // 其他属性配置
}
此时,自定的路由规则也可以到外部拿到了。
// xxx.vue
import { $routes } from '@/router'
console.log($routes)
以上为个人整理,如有错误请指正,谢谢