一般我们使用组件内使用组件时,直接import *** from *** 等一些操作,但是对于导入量大或动态渲染时是一个很头疼的问题,下面是我个人使用的处理方式:
开始:众所周知,vue内存在一个计算属性:computed,这是一个很好的属性,若有不懂我就不细说,推荐看下这篇文章:https://www.cnblogs.com/gunelark/p/8492468.html
代码如下:
1、计算属性内添加一个计算方法;用于动态加载组件
computed:{
loadertpl(){
return () => import('@/components/library/public/'+this.tpl+'/')
}
},
这里值得注意的是:
1、this.tpl 是data内的一个变量,我用于动态加载目录组件库下的组件名,用于watch等操作的
2、components/library/public 这是我定义的组件库目录,内的每个目录就是一个闭合组件
2、其实到这里,懂得使用computed属性的伙伴其实都知道怎么做了,下面我就在methods内定义一个方法使用loadertpl:
methods:{
init:function(){
const self = this;
self.loadertpl().then(()=>{
// 动态加载模板
self.rendertpl = ()=>self.loadertpl();
}).catch(()=>{
// 模板不存在404时处理
self.rendertpl = ()=>import('@/components/library/public/404/');
})
},
},
说明:
1、Promise 语法,动态加载模板,模板不存在时直接使用404显示
2、rendertpl 是我在DOM页面渲染的组件名
3、页面使用,渲染动态组件:
<component v-bind:is="rendertpl " v-if="rendertpl "></component>
### 最后奉上一个完整的vue页面:
<template>
<div>
<component v-bind:is="contpl" v-if="contpl"></component>
</div>
</template>
<script type="text/javascript">
export default {
name:'Dynamic',
props:['cpname'],
data:function() {
return {
rendertpl:null,
tpl:''
}
},
watch:{
"cpname":function(){
this.tpl = this.cpname;
this.init();
}
},
computed:{
loadertpl(){
return () => import('@/components/library/public/'+this.tpl+'/')
}
},
methods:{
init:function(){
const self = this;
self.loadertpl().then(()=>{
// 动态加载模板
self.rendertpl = ()=>self.loadertpl();
}).catch(()=>{
// 模板不存在404时处理
self.rendertpl = ()=>import('@//components/library/public/404/');
})
},
},
mounted(){
this.init();
},
}
</script>
<style lang="scss" scoped></style>
#由于升级导致import动态引入组件会报错,现提供一个新的案例
1/组件
<component v-bind:is="loadertpl " v-if="loadertpl "></component>
2/js
data() {
return {
tpl: '',
}
},
computed: {
loadertpl() {
const self = this;
if(!self.tpl) return "";
return function (resolve) {
require(['./site/' + self.tpl + '.vue'], resolve)
};
}