vue引入組件批量引入是怎么回事呢捅儒?vue引入組件相信大家都很熟悉查刻,只要import一下就行了,但是vue引入組件批量引入是怎么回事呢秧饮,下面就讓小編帶大家一起了解吧映挂。
vue引入組件批量引入,其實(shí)就是用webpack 的 require.context引入盗尸,大家可能會很驚訝vue引入組件怎么會用webpack引入呢柑船?但事實(shí)就是這樣,小編也感到非常驚訝泼各。
這就是關(guān)于vue引入組件批量引入的事情了鞍时,大家有什么想法呢,歡迎在評論區(qū)告訴小編一起討論哦扣蜻!
例子:
批量引入vue 組件掛到components里
const ctx = require.context('./ljxt', true, /\.vue$/)
const routes = {};
ctx.keys().forEach(key=>{
const name = key.split("/")[2].split(".")[0];
routes[name] = ctx(key).default || ctx(key);
});
console.log(routes)
export default {
components: {
bzmodel,
...routes,
},
data(){
return{
isShow:1,
params:"",
}
}
}
template里面
批量使用組件
<component v-if='isShow' :params ="params" :is="abc[key]"></component>
還有一種情況就是批量exports哦逆巍,也是很實(shí)用的小功能呢
const ctx = require.context('./store', false, /\.js$/)
const importAll = context => {
const map = []
for (const key of context.keys()) {
let b = context(key)
b.default?map.push(b.default):map.push(b)
}
return map
}
let model = importAll(ctx)
console.log(model)
export default model
例子3 批量引入后注冊到Vue全局里邊
module.exports = (Vue)=>{
const files = require.context('.', true, /\.vue$/);
files.keys().forEach((key) => {
const componentModule = files(key);
//key值為./identityInformation.vue 需要變成identityInformation
//const componentName = key.replace(/^\.\/|\.vue$/g, '');
//考慮到以前iphone釘釘瀏覽器webpack打包后正則有失效的情況,還是使用簡單的split
const componentName = (key.split("./")[1]).split(".vue")[0]
Vue.component(key, componentModule.default);
});
}