1. 程式人生 > 實用技巧 >如何批量匯入元件,並在vue-router中批量設定?

如何批量匯入元件,並在vue-router中批量設定?

import auth from './auth'
import App from './components/App.vue'
import About from './components/About.vue'
import Dashboard from './components/Dashboard.vue'
import Login from './components/Login.vue'

const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  routes: [
    { path: '/about', component: About },
    { path: 
'/dashboard', component: Dashboard, beforeEnter: requireAuth }, { path: '/login', component: Login }, { path: '/logout', beforeEnter (to, from, next) { auth.logout() next('/') } } ] })

如上所示,在main.js中,需要多少個頁面,就得Import幾次,routes中設定幾次。假設頁面多達數十上百,則太過繁瑣,有無批量設定的辦法呢?

搜尋後的結果,vue官網,等等,皆指出可利用webpack提供的require.context()介面,批量匯入

//如果你恰好使用了 webpack (或在內部使用了 webpack 的 Vue CLI //3+),那麼就可以使用 require.context 只全域性註冊這些非常通用的基礎組//件。這裡有一份可以讓你在應用入口檔案 (比如 src/main.js) 中全域性匯入//基礎元件的示例程式碼:
import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

const requireComponent = require.context(
  // 其元件目錄的相對路徑
'./components', // 是否查詢其子目錄 false, // 匹配基礎元件檔名的正則表示式 /Base[A-Z]\w+\.(vue|js)$/ ) requireComponent.keys().forEach(fileName => { // 獲取元件配置 const componentConfig = requireComponent(fileName) // 獲取元件的 PascalCase 命名 const componentName = upperFirst( camelCase( // 獲取和目錄深度無關的檔名 fileName .split('/') .pop() .replace(/\.\w+$/, '') ) ) // 全域性註冊元件 Vue.component( componentName, // 如果這個元件選項是通過 `export default` 匯出的, // 那麼就會優先使用 `.default`, // 否則回退到使用模組的根。 componentConfig.default || componentConfig ) })
//把上面的程式碼儲存為單獨的globalcomponentsjs檔案,在main.js中匯入

import './globalcomponentsjs'

//此時,在app.vue中,可直接使用那些元件,比如匯入了About.vue
<About/>

//遺憾的是,這樣匯入的元件,在routes中,無法使用

-----------------------------------------------------------------------------------------分割線------------------------------------------------------------------

官網的辦法,無法解決在router中批量匯入元件的問題,搜尋後,終於找到答案:

//https://segmentfault.com/q/1010000015301741
//答案引用地址見上面
//再一次提到require.context,按照一定結構去放對應檔案就可以,可以適當
//改變路由定義,支援懶載入
const routes = [
    { path: '*', redirect: '/index' }
  ];
 importPages(require.context('./views', true, /\.vue$/,'lazy'))
 function importPages (r) {
    r.keys().forEach(key => {
      routes.push({ path: (key.split('.'))[1], component: ()=>r(key)})
    });
  }