1.require动态引入
1.背景
(1)组件不确定
(2)多个组件结合component标签动态切换
2.应用demo
<article>
<component ref="asyncComp" :is="compName"></component>
</article>
onTabClick(item) {
this.currentTab = item;
require(['@views/dashboard/components/' + item.path + '.vue'], (res) => {
this.compName = res.default;
this.$nextTick(() => {
this.$refs.asyncComp.edit({
factoryId: this.queryParam.factoryId
})
})
})
}
// 结合弹窗,基础modal
<template>
<a-modal
class="BaseModal"
:width="width"
style="min-width: 800px"
:visible="visible"
:okButtonProps="{ props: {disabled: disableSubmit} }"
:confirmLoading="confirmLoading"
:footer="footer"
@ok="handleOk"
@cancel="handleCancel"
cancelText="关闭">
<template slot="title">
<div style="height: 25px">
{{name}}
</div>
</template>
<a-spin :spinning="spinning">
<component ref="comp" :key="compName" :is="compName" @ok="handleCancel"></component>
</a-spin>
</a-modal>
</template>
<script>
const ModalBaseAttr = {
width: 900,
visible: false,
confirmLoading: false,
loading: false,
disableSubmit: false,
videoSource: [],
footer: false,
labelCol: {
xs: { span: 24 },
sm: { span: 6 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 16 },
},
dayFormat: 'YYYY-MM-DD',
monthFormat: 'YYYY-MM',
spinning: false,
url: {
list: '/video/tVideo/list'
}
}
export default {
name: 'BaseModal',
props: {
infoId: {
type: String,
default: ''
}
},
data() {
return {
compName: '',
...ModalBaseAttr,
width: '70%',
name: '',
url: {
add: 'equipment/equipmentTvideo/add',
list: '/video/tVideo/list'
},
videoSource: [],
model: {}
};
},
methods: {
add() {
this.edit({})
},
edit(type) {
// title: type.name,
// compName: 'AnalysisUserList',
// footer: false,
Object.assign(this, type)
this.$nextTick(() => {
this.visible = true;
this.$nextTick(() => {
this.$refs.comp.edit && this.$refs.comp.edit(type.record)
})
})
},
handleOk() {
this.$refs.comp.handleOk();
},
handleCancel() {
this.visible = false
}
}
};
</script>
<style scoped lang="less">
.BaseModal {
}
</style>
3.注意点
(1)无论是import还是require都是异步的
(2)建议组件提供统一的入口,例如edit()
(3)在编译阶段,被动编译引入目录下的所有文件(@views/dashboard/components/),即使没有使用
(4)初始目录不确定下无法动态引入