Vue-component实现动态组件切换传值问题
2022-06-22 本文已影响0人
睿丶清
Vue-component实现动态组件切换传值问题
使用动态组件
vue提供了一个内置的 <component> 组件, 专门用来实现动态组件的渲染 。通俗的讲 component属于占位符的,在指定条件下替换成指定的组件即可
创建<component>占位
<template>
<div class="app-container">
<h1>App 根组件</h1>
<hr />
<div class="box">
<!-- 渲染 Left 组件和 Right 组件 -->
<keep-alive include="Left">
<component :is="nameCom" :currentProp="this.currentProp"></component>
</keep-alive>
</div>
<Button @click="changeLeft">Left</Button>
<Button @click="changeRight">Right</Button>
</div>
</template>
:is属性指定当前设置组件的变量名称,且该变量名称需要在data节点下定义
keep-alive 嵌套的组件实现切换状态保活
<script>
import Left from "./components/Left.vue";
import Right from "./components/Right.vue";
export default {
data() {
return {
nameCom: 'Left',
};
},
computed: {
currentProp() {
switch (this.nameCom) {
case 'Left':
return { name: "Rose", age: 12, address: "BJ" };
case 'Right':
return { nick: "Rose", age: 12, sex: "woman" };
default:
return { name: "Rose", age: 12, address: "BJ" };
}
},
},
components: {
Left,
Right,
},
methods: {
changeLeft() {
this.nameCom = "Left";
},
changeRight() {
this.nameCom = "Right";
},
},
};
</script>
script标签下实现了组件的导入、注册、切换组件是传值的功能(父组件给子组件传值使用自定义属性),子组件定义props接收属性,当前属性类型为对象格式,方便不同的业务场景需不同的业务参数,将其构建在对象中,进行传递。
Left组件:
<template>
<div class="left-container">
<h3>Left 组件</h3>
<p>{{ count }}</p>
<p>{{ transmitData }}</p>
<button @click="add">add</button>
</div>
</template>
<script>
export default {
// name:'LeftCom',
data() {
return {
count: 0,
transmitData:{}
};
},
methods: {
add() {
this.count++;
},
},
props: {
currentProp: {
type: Object,
},
},
created(){
this.transmitData = this.currentProp
console.log("Left"+JSON.stringify(this.currentProp));
}
};
</script>
Right组件:
<template>
<div class="right-container">
<h3>Right 组件</h3>
<p>{{transmitData}}</p>
</div>
</template>
<script>
export default {
// name:'RightCom'
props:{
currentProp:{
type:Object
}
},
data(){
return{
transmitData:{}
}
},
created(){
this.transmitData=this.currentProp
console.log("Left"+JSON.stringify(this.currentProp));
},
};
</script>