实现目标:分模块添加时候组件封装
1.父组件内容
<template>
<div>
<article>
{{ tmpjson.id }}:{{ tmpjson.name }}
<button @click="reWriteToChild">点击</button>
<form-child v-model="tmpjson"></form-child>
</article>
</div>
</template>
<script>
import formChild from "./formChild";
export default {
name: "Main",
components: {
formChild,
},
data() {
return {
tmpjson: { name: "11", id: "11" },
};
},
methods: {
reWriteToChild() {
this.tmpjson = { name: "33", id: "33" };
},
},
};
</script>
2.子组件内容 尝试运行代码,不必纠结,原理看(官网v-model原理)即可
<template>
<div>
<article>
<input type="text"
v-model="testdata.name"
@change="changeName" />
</article>
</div>
</template>
<script>
export default {
name: "formChild",
props: {
tmpjson: Object,
},
model: {
prop: "tmpjson",
event: "changedata",
},
data() {
return {
testdata: {},
};
},
watch: {
tmpjson(val, oldVal) {
if (val != oldVal) {
this.testdata = this.tmpjson;
}
},
},
methods: {
changeName() {
this.testdata.id = "999";
this.$emit("changedata", this.testdata);
},
},
};
</script>