組件
很多時候我們組件都是這樣引入的:
微信截圖_20200420165243.png
當組件重復使用次數較多時,每個頁面都需要這樣引入一遍曙咽,就比較冗余省店,此時可以使用require.context()來全局注冊,這樣就不用每個頁面都引入一遍了宙拉。
附上代碼:
function changeStr(str){
return str.charAt(0).toUpperCase() + str.slice(1);
}
//第一個參數的當前目錄宾尚,第二個參數是否匹配子目錄,第三次參數正則匹配.vue結尾的文件
const requireComponent = require.context('./', false, /\.vue$/)
console.log(requireComponent.keys())
const install = (Vue) =>{
requireComponent.keys().forEach(fileName => {
let config = requireComponent(fileName);
let componentName = changeStr(
fileName.replace(/^\.\//,'').replace(/\.\w+$/,'') //獲取到的是./button.vue 此步去掉前面的額./和后面的.vue 只保留button當組件名稱
)
console.log(componentName)
Vue.component(componentName, config.default || config)
});
}
export default{
install
}
通用組件目錄如下:
微信截圖_20200420173422.png
然后在main.js里引用一下即可谢澈,此時就不用進行繁瑣的組件導入聲明了煌贴,直接可以調用組件如下:
<template>
<div>
<Child1></Child1>
<Child2></Child2>
</div>
</template>
<script>
export default {
data () {
return {
}
},
components: {},
computed: {},
created () {},
mounted () {},
methods: {},
}
</script>
<style lang='stylus' scoped>
</style>
路由
路由同理,正式開發(fā)項目中不應該把所有路由放在一個文件里锥忿,不好維護牛郑,而是應該把路由按照模塊劃分,同時用上require.context()一勞永逸敬鬓,只需要操作模塊路由文件就可以了淹朋。
demo目錄劃分如下:
微信截圖_20200421101951.png
index.js文件代碼如下:
/*
* @Description: In User Settings Edit
* @Author: your name
* @Date: 2019-08-28 14:54:47
* @LastEditTime: 2020-04-21 10:17:12
* @LastEditors: Wangjianan
*/
import Vue from 'vue'
import Router from 'vue-router'
import login from '../views/login.vue'
Vue.use(Router)
const routerList = []
function importAll(r){
r.keys().forEach(
(key) => routerList.push(r(key).default)
)
}
importAll(require.context('./',true,/\.router\.js/)); //匹配當前目錄下的.router.js結尾的文件
console.log(routerList)
export default new Router({
routes: [
{
path: '/',
name: 'login',
component: login
},
{
path: '/main',
name: 'main',
component: () => import(/* webpackChunkName: "about" */ '../views/main.vue'),
redirect: '/index',
children: [
...routerList
]
}
]
})
模塊路由文件index.router.js如下:
export default {
path: '/index',
name: 'index',
component: () => import('../views/index.vue'),
children:[]
}
這樣以后就只需要在router文件夾下面新增如user.router.js,然后在里面寫路由就可以了钉答,index.js就不用動了础芍。