这次测试只是一个基本类型的父子组件之间的传参,以及子组件watch监听父组件的传值,子组件修改父组件的传值。
1.在父组件中引入子组件,然后绑定传值;
2.子组件要改变父组件的传值,需要通过emit事件触发改变值,首先需要在父组件中在需要改变值的子组件上绑定值改变的事件,并且定义方法接收值
父组件
<template>
<div class="container">
<test-components :info="switchValue" @changeValue='componentChange($event)'></test-components>
<el-button type="primary" @click="setValue">{{
switchValue ? "关闭" : "打开"
}}</el-button>
</div>
</template>
<script>
import testComponents from "./testComponents";
import TestComponents from './testComponents.vue';
export default {
components: {
testComponents,
},
data() {
return {
switchValue: false,
};
},
methods: {
setValue() {
this.switchValue = !this.switchValue;
},
componentChange(status){
console.log('子组件传值',status)
this.switchValue = status
}
},
};
</script>
<style scoped lang="scss">
</style>
1.子组件中首先需要定义props的字段名称以及类型;
2.监听传值的变化,可以用watch监听
3.子组件若要改变父组件的传值,不能直接改变,需要emit事件触发父组件的函数,然后间接的改变父组件的值
子组件:
<template>
<div class="info-content">
<el-switch
v-model="indexValue"
active-color="#13ce66"
inactive-color="#ff4949"
@change="setValue"
>
</el-switch>
</div>
</template>
<script>
export default {
props: {
info: {
type: Boolean,
default: "",
},
},
data() {
return {
indexValue: false,
};
},
//监听父组件传递的值
watch: {
info: {
handler(newValue, oldValue) {
console.log("父组件传递的值", newValue, oldValue);
this.indexValue = newValue;
},
deep: true,
},
},
methods: {
setValue() {
this.$emit("changeValue", this.indexValue);
},
},
};
</script>
<style scoped lang='scss'>
.info-content {
width: 300px;
height: 300px;
border: 1px solid #e5e5e5;
border-radius: 10px;
}
</style>