1、sync修饰符(v2.3.0+ 新增)

父组件代码

1
2
3
4
5
<div>
<child :value.sync="doc"></child>
<div>father: <input type="text" v-model="doc" /></div>
<div>result: <span v-html="doc"></span></div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
import Child from "@/components/Bb-child.vue";
export default {
name: "Bb",
components: {
Child
},
data() {
return {
doc: "输入试试"
};
}
};

子组件代码

1
2
3
<div>
<div>child: <input type="text" v-model="val" @input="iptInput" /></div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
export default {
name: "Bb-child",
props: {
value: String
},
data() {
return {
val: this.value
};
},
watch: {
value(newVal) {
this.val = newVal;
}
},
methods: {
iptInput() {
this.$emit("update:value", this.val);
}
}
};

2、老版本

父组件代码

1
2
3
4
5
<div>
<child :value="doc" @input="oninput"></child>
<div>father: <input type="text" v-model="doc" /></div>
<div>result: <span v-html="doc"></span></div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import Child from "@/components/Bb-child.2.vue";
export default {
name: "Bb",
components: {
Child
},
data() {
return {
doc: "输入试试"
};
},
methods: {
oninput(val) {
this.doc = val;
}
}
};

子组件代码

1
<div>child: <input type="text" v-model="val" @input="iptInput" /></div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
export default {
name: "Bb-child.2",
props: {
value: String
},
data() {
return {
val: this.value
};
},
watch: {
value(newVal) {
this.val = newVal;
}
},
methods: {
iptInput() {
this.$emit("input", this.val);
}
}
};