需求:
根据不同类型,显示不同页面
原始代码,菜逼写法
<template>
<!-- 弹窗插件 -->
<el-dialog :title="title" :visible.sync="openExchange" width="700px" append-to-body :before-close="handleClose" :close-on-click-modal="false"><div v-if="this.options.layout=='exchange'" ><dialog-exchange :options = this.options /></div><div v-else-if="this.options.layout=='webpage'" ><dialog-webpage :options = this.options /></div><div v-else-if="this.options.layout=='annex'" ><dialog-annex :options = this.options /></div><div slot="footer" class="dialog-footer"><el-button type="primary" @click="updateData">确 定</el-button><el-button @click="handleClose">取 消</el-button></div>
</el-dialog>
</template><script>
import dialogExchange from './components/dialogExchange'
import dialogWebpage from './components/dialogWebpage'
import dialogAnnex from './components/dialogAnnex'export default {components: {dialogExchange,dialogWebpage,dialogAnnex,},data() {openExchange: false,title: "",options: [],},
}
</script>
阅读过官方文档,了解到动态组件和异步组件注册
采用动态注册组件,更新后代码
<template>
<!-- 弹窗插件 -->
<el-dialog :title="title" :visible.sync="openExchange" width="700px" append-to-body :before-close="handleClose" :close-on-click-modal="false"><!-- 使用 component --><component:is="this.options.layout":options="this.options"/></el-dialog>
</template><script>export default {components: {},data() {openExchange: false,title: "",options: [],componentsType: [{ name:"exchange", value: './components/dialogExchange' },{ name:"webpage", value: './components/dialogWebpage' },{ name:"annex", value: './components/dialogAnnex' },]},created() {this.registerComponent();},methods: {// 注册组件async registerComponent() {this.componentsType.forEach(element => {if (!this.$options.components[element.name]) {try {this.$options.components[element.name] = (resolve) => require([`${element.value}`], resolve);} catch (error) {this.$modal.alertError("注册组件发生异常:" + error);console.warn("注册组件发生异常:" + error);}}});},}
}
</script>
后续维护只要往componentsType添加组件类型和地址就可以了