修訂:新的方式使用了 process.cwd() 替代了 __dirname,能夠隨意在外部引用自定的 routes
首先,在 nuxt.config.js 中,有 router 屬性可配置 ,且 router 可配置對(duì)象中有 extendRoutes 擴(kuò)展路由方法。
1:在根目錄下新增 router 文件夾并創(chuàng)建 Index.js 文件。(就像vue中一樣)
2:引入 path 模塊,并簡(jiǎn)單封裝成resolve方法,這里不要用 __dirname,否則路由暴露出去調(diào)用時(shí) 刷新頁(yè)面會(huì)出錯(cuò),因?yàn)樗⑿聲r(shí)__dirname是不存在的。
這里要用 process.cwd(),process.cwd() 會(huì)拿到你項(xiàng)目運(yùn)行時(shí)所在的文件目錄。
// 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:自定義路由相關(guān)屬性(就像vue中定義的一樣)
// router/index.js
// 簡(jiǎn)單定義一下
export const $routes = [
{
path: '/',
name: 'Home',
component: resolve('pages/home/index.vue'),
meta: {
title: '首頁(yè)',
icon: 'icon-home'
}
},
{
path: '/dashboard',
component: resolve('pages/dashboard/index.vue'),
meta: {
title: '控制臺(tái)',
icon: 'icon-dashboard'
},
children: [
{
path: '',
name: 'dashboard-cloud',
component: resolve('pages/dashboard/cloud/index.vue'),
meta: {
title: '云云云',
icon: 'icon-cloud'
}
}
]
}
]
4:定義 extendRoutes 方法,清除原有的nuxt自動(dòng)生的路由,添加自己的新路由(最重要的一步), routes.length = 0
// router/index.js
const extendRoutes = (routes) => {
routes.length = 0
routes.push(...$routes)
}
5:最后定義router對(duì)象并暴露出去,然后直接在 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: '首頁(yè)',
icon: 'icon-home'
}
},
{
path: '/dashboard',
component: resolve('pages/dashboard/index.vue'),
meta: {
title: '控制臺(tái)',
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 自己生成的路由,這里不要用 空數(shù)組 賦值
routes.push(...$routes)
}
export default { base: '/', extendRoutes }
// nuxt.config.js
import router from './router'
export default {
..., // 其他屬性配置
router,
... // 其他屬性配置
}
此時(shí),自定的路由規(guī)則也可以到外部拿到了。
// xxx.vue
import { $routes } from '@/router'
console.log($routes)
以上為個(gè)人整理,如有錯(cuò)誤請(qǐng)指正,謝謝