vue中动态组件
有的时候,在不同组件之间进行动态切换是非常有用的,比如在一个多标签的界面里:效果如下
灰色的两个按钮A,B 用于切换组件,红色边框和蓝色边框的是具体组件的样子;
具体代码:
组件A:
<template>
<div style="width:80px;height:60px;border:1px solid red;margin: 0 auto;">组件A</div>
</template>
<script>
export default {
name: "compa",
data() {
return {};
},
methods: {},
};
</script>
<style lang="less" scoped>
</style>
组件B类似,只是style的宽高等不一致;
父组件代码:
<template>
<div>
<component :is="currentView"></component>
<button @click="handleChangeView('compa')">A</button>
<button @click="handleChangeView('compb')">B</button>
</div>
</template>
<script>
import compa from "./compA.vue";
import compb from "./compB.vue";
export default {
name: "Table",
components: { compa, compb, },
data() {
return {
currentView: "compa",
};
},
methods: {
handleChangeView(component) {
this.currentView = component;
},
},
};
</script>
说明:组件切换主要是通过 Vue 的 <component>
元素加一个特殊的 is
attribute 来实现:
还没有评论,来说两句吧...