1)子组件
<template>
<div>
<!-- 临时对象和input控件绑定 -->
<input type="text" v-model="studentTemp.name" />
<input type="text" v-model="studentTemp.address" />
<el-button type="primary" @click="setValue()">组件内部设置对象</el-button>
</div>
</template>
<script>
export default {
name: "MyTest",
data() {
return {
// 将传参赋值给临时对象
studentTemp: this.student,
};
},
model: {
prop: "student",//参数名
event: "change",//子组件要更新父组件值需要注册的方法
},
props: {
// 获取传参
student: {},
},
watch: {
// 监听临时变量变化是将数据传递给母页面
studentTemp(val) {
this.$emit("change", val);
},
},
methods: {
// 重置临时变量
setValue() {
this.studentTemp.name = "李四";
this.student.address = "江苏";
},
},
mounted() {},
};
</script>
<style scoped>
</style>
2)母页面vue
<template>
<div>
<!-- 使用自定义组件,传递参数 -->
<my-test v-model="student"></my-test>
<el-button type="primary" @click="getValue();">组件外部获取对象</el-button>
</div>
</template>
<script>
import PlanDemo from '../../scripts/Plan/Demo';
export default {
...PlanDemo,
};
</script>
3)母页面script
import MyTest from '../../components/MyTest';
export default {
components: { MyTest },
data() {
return {
student: { name: '', address: '' },
}
},
methods: {
// 获取对象
getValue() {
alert(JSON.stringify(this.student));
}
},
mounted() {
// 参数赋值
this.student.name = '张三';
this.student.address = '浙江';
},
};
4)效果
a)初始化效果
b)单击组件内部按钮“组件内部设置对象”修改临时对象效果
c)单击组件外部按钮“组件外部获取对象”获取对象效果