如何批量導入組件,並在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)})
    });
  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM