vue2.0父子组件双向绑定

时间:2022-12-21 13:41:03

父组件代码如下。这里要注意的有:
1. 父组建使用msg向子组件传递数据。
2. 子附件向父附件发送xxx消息,父组件收到消息后用abc方法来处理。

<template>
<div>
<input type="text" v-model="msg">
<br>
<child :inputValue="msg" v-on:xxx="abc"></child>
</div>
</template>
<style>

</style>
<script>
import child from './childCom.vue'
export default{
data(){
return {
msg: '请输入'
}
},
components: {
child
},
methods: {
abc: function(data){
console.log("message received: " + data);
this.msg = data;
}
}
}
</script>

子组件代码如下。
1. 子组件无法直接改变父组件传来的inputValue。因此,要自己建一个变量来将inputValue值传给它。
2. 子组件使用watch来检测inputValue的值的变化。
3. 子组件使用change事件来触发向父组件传递消息。但是不知道为啥只有按回车才会触发change事件。有知道的告诉一下。谢谢!

<template>
<div>
<p>
{{inputValue}}</p>
<input type="text" v-model="msg" @change="onInput">
</div>
</template>
<style>

</style>
<script>
export default{
props: {
inputValue: String
},
data () {
return {
msg: this.inputValue
}
},
watch: {
inputValue: function(){
this.msg = this.inputValue
}
},
methods: {
onInput: function(){
this.$emit('xxx', this.msg);
console.log("message sent: " + this.msg);
}
}
}
</script>