VUE2v-model父子组件通信
时间: 2024-03-07 18:45:07 浏览: 111
在Vue2中,v-model是一种用于实现父子组件通信的指令。它可以将父组件的数据传递给子组件,并且在子组件中修改后可以将修改后的值传递回父组件。
具体使用v-model进行父子组件通信的步骤如下:
1. 在父组件中,使用v-model指令绑定一个变量,并将该变量作为prop传递给子组件。例如:
```html
<template>
<div>
<child-component v-model="message"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
message: ''
};
}
};
</script>
```
2. 在子组件中,接收父组件传递的prop,并使用`$emit`方法将修改后的值传递回父组件。例如:
```html
<template>
<div>
<input type="text" :value="value" @input="updateValue($event.target.value)">
</div>
</template>
<script>
export default {
props: ['value'],
methods: {
updateValue(newValue) {
this.$emit('input', newValue);
}
}
};
</script>
```
通过以上步骤,就可以实现父子组件之间的双向数据绑定。当子组件中的输入框内容发生变化时,会触发`updateValue`方法,然后通过`$emit`方法将新的值传递回父组件,父组件中的`message`变量也会随之更新。
阅读全文
相关推荐


















