欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue3.0基于views批量實現(xiàn)動態(tài)路由的方法(示例代碼)

 更新時間:2024年12月17日 11:19:41   作者:kirinlau  
以前vue項目中也有很多實現(xiàn)動態(tài)路由的方法,比如有一些項目涉及權限的可能會使用api請求路由數(shù)據(jù)在來createRouter,或者本地構建使用routes.push來動態(tài)構建路由, 今天介紹一種新的方式來基于某個文件夾批量構建動態(tài)路由的方法,感興趣的朋友一起看看吧

以前vue項目中也有很多實現(xiàn)動態(tài)路由的方法,比如有一些項目涉及權限的可能會使用api請求路由數(shù)據(jù)在來createRouter,或者本地構建使用routes.push來動態(tài)構建路由, 今天介紹一種新的方式來基于某個文件夾批量構建動態(tài)路由的方法:
假如項目scr基礎目錄偽代碼如下:

src
├── views
│   ├── Home.vue
│   ├── About.vue
│   └──...(其他組件.vue文件)
├── main.js
└── router
    └── index.js

配置router

src/router/index.js(路由配置文件,路徑可根據(jù)實際情況調整)中進行如下基礎配置:

import { createRouter, createWebHistory } from 'vue-router'
import.meta.glob('../views/*.vue') // 用于動態(tài)導入組件
const routes = []
const router = createRouter({
  history: createWebHistory(),
  routes
})
export default router

動態(tài)生成路由

import { createRouter, createWebHistory } from 'vue-router'
import.meta.glob('../views/*.vue')
const routes = []
const addRoutesFromViewsFolder = () => {
  const componentModules = import.meta.glob('../views/*.vue')
  for (const path in componentModules) {
    const componentName = path.split('/').pop().replace('.vue', '')
    const routePath = `/${componentName.toLowerCase()}`
    const routeConfig = {
      path: routePath,
      name: componentName,
      component: componentModules[path],
      meta: {
        title: obj.componentName,
        needToken: obj.needToken
      }
    }
    routes.push(routeConfig)
  }
}
addRoutesFromViewsFolder()
const router = createRouter({
  history: createWebHistory(),
  routes
});
export default router;

在 main.js 中使用路由

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router);
app.mount('#app');

總結:

  • 首先通過import.meta.glob(‘…/views/*.vue’)獲取views文件夾下所有.vue組件的模塊引用
  • 然后遍歷這些模塊引用,分割提取出組件名稱,并根據(jù)一定規(guī)則生成路由配置對象,包含path(路由路徑)、name(路由名稱)以及component(對應的組件)
  • 接著將這些路由配置對象添加到routes數(shù)組中,并基于這個routes數(shù)組創(chuàng)建vue-router實例
  • 這樣,Vue 3 應用就可以根據(jù)views文件夾下的組件動態(tài)生成路由了,當添加新的組件到views文件夾時,只要符合上述掃描規(guī)則,就會自動被添加到路由配置中,無需手動逐個去配置路由,也無須知道別人添加了什么路由

注意:

  • 代碼中的路徑等都是基于常見的項目結構示例,實際項目中你可能需要根據(jù)真實的文件夾結構和組件命名等情況來調整相關代碼,比如import.meta.glob中的路徑部分。
  • 另外菜單渲染遍歷使用的是meta最好能寫個映射表,這樣就可以和當前的routes對象自動對應
  • 還有就是對于更復雜的路由需求,比如路由嵌套、路由參數(shù)傳遞等,還需要進一步在路由配置和組件中進行相應的擴展和實現(xiàn)。

備注:vue3中引入了import.meta.的概念可以有很多的用法比如環(huán)境變量、當前url、當前組件等

到此這篇關于vue3.0基于views批量實現(xiàn)動態(tài)路由的方法(示例代碼)的文章就介紹到這了,更多相關vue動態(tài)路由內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論