最常用的不同组件之间双向绑定的方式是使用 v-model
结合自定义事件和 props。这种方式可以使得代码更加简洁和易于理解。
具体来说,可以通过在子组件中使用 v-model
,并且在子组件中触发 update:modelValue
事件来实现双向绑定。
<!-- ChildComponent.vue -->
<template>
<div>
<label>Child Component:</label>
<input v-model="innerValue">
</div>
</template>
<script>
export default {
props: ['modelValue'],
data() {
return {
innerValue: this.modelValue
};
},
watch: {
modelValue(newValue) {
this.innerValue = newValue;
}
},
methods: {
updateValue() {
this.$emit('update:modelValue', this.innerValue);
}
},
created() {
this.$watch('innerValue', this.updateValue);
}
};
</script>
<!-- ParentComponent.vue -->
<template>
<div>
<label>Parent Component:</label>
<ChildComponent v-model="parentValue" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentValue: ''
};
}
};
</script>
在这个示例中,父组件中的 parentValue
通过 v-model
传递给了子组件,并且在子组件中通过 update:modelValue
事件更新。子组件内部使用 v-model
绑定了 innerValue
,然后在内部监视器中监视 innerValue
的变化,并在变化时触发 update:modelValue
事件向父组件传递最新的值。
这种方式保持了 Vue.js 的单向数据流原则,并且使得组件之间的数据传递更加清晰和简洁。