修訂:新的方式使用了 process.cwd()
替代了 __dirname
搬男,能夠隨意在外部引用自定的 routes
首先,在 nuxt.config.js
中彭沼,有 router
屬性可配置 缔逛,且 router
可配置對象中有 extendRoutes
擴展路由方法。
1:在根目錄下新增 router 文件夾并創(chuàng)建 Index.js 文件。(就像vue中一樣)
2:引入 path 模塊褐奴,并簡單封裝成resolve方法按脚,這里不要用 __dirname
,否則路由暴露出去調(diào)用時 刷新頁面會出錯敦冬,因為刷新時__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:自定義路由相關(guān)屬性(就像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 自己生成的路由猿妈,這里不要用 空數(shù)組 賦值
routes.push(...$routes)
}
export default { base: '/', extendRoutes }
// nuxt.config.js
import router from './router'
export default {
..., // 其他屬性配置
router,
... // 其他屬性配置
}
此時,自定的路由規(guī)則也可以到外部拿到了巍虫。
// xxx.vue
import { $routes } from '@/router'
console.log($routes)
以上為個人整理彭则,如有錯誤請指正,謝謝