1,定义:
- 动态组件就是将几个组件放在一个挂载点下,这个挂载点就是标签,其需要绑定is属性,属性值为父组件中的变量,变量对应的值为要挂载的组件的组件名,然后根据父组件里某个变量来动态显示哪个,也可以都不显示,
2,使用:
<component>元素是vue 里面的一个内置组件。在里面使用 v-bind: is,可以实现动态组件的效果。
<component :is="currentComponent"></component>
3,例子:
<!--
* @Descripttion: vue动态组件
* @version:
* @Author: zhangfan
* @email: 2207044692@qq.com
* @Date: 2020-07-03 09:10:28
* @LastEditors: zhangfan
* @LastEditTime: 2020-07-13 17:10:31
-->
<template>
<div class="container">
<component v-bind:is="currentTabComponent"></component>
<div v-for="(item,index) in groupList" :key="index">
<el-button type="primary" @click="choosencomp(item)">{{item.name}}</el-button>
</div>
</div>
</template>
<script>
import componentdemo1 from "@/components/componentdemo1";
import componentdemo2 from "@/components/componentdemo2";
import componentdemo3 from "@/components/componentdemo3";
export default {
components: {
componentdemo1,
componentdemo2,
componentdemo3
},
data() {
return {
currentTabComponent: "componentdemo1",
groupList: [
{
name: "组件一",
componentName: "componentdemo1"
},
{
name: "组件二",
componentName: "componentdemo2"
},
{
name: "组件三",
componentName: "componentdemo3"
}
]
};
},
methods: {
choosencomp(data) {
this.currentTabComponent = data.componentName;
}
}
};
</script>
<style scoped lang="less">
</style>
4,在动态组件上使用 keep-alive:
<!-- 失活的组件将会被缓存!-->
<keep-alive>
<component v-bind:is="currentTabComponent"></component>
</keep-alive>