对于一些特殊的软件系统会涉及大量模板,比如不同的设备采集原始数据的页面,如果存在成千种类的设备,那么对应原始数据采集模板页面也会有上千个, 对于普通的vue文件import上千个modules是不可想象的,下面介绍一个利用循环语句加载模板的方法。
<template>
<div id="example">
<input v-model="pointedView" type="text" />
<button @click="change">切换页面</button>
<component :is="currentView"></component>
</div>
</template>
<script>
import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'
const requireComponent = require.context(
'@/components/children',
false,
/\.(vue|js)$/
)
requireComponent.keys().forEach(fileName => {
const componentConfig = requireComponent(fileName)
const componentName = upperFirst(
camelCase(
fileName
.split('/')
.pop()
.replace(/\.\w+$/, '')
)
)
Vue.component(
componentName,
componentConfig.default || componentConfig
)
})
export default {
name: 'example',
data: function () {
return {
pointedView: '',
currentView: ''
}
},
methods: {
change () {
this.currentView = this.pointedView
}
}
}
</script>
相应在components/children下添加模板compontent1, compontent2, compontent3...