Vue3 中使用 v-model 实现父子组件双向绑定与通信
在 Vue3 中,可以使用 v-model 来实现父子组件之间的双向绑定和通信。\n\n在父组件中,可以使用 v-model 来绑定一个值,并将这个值传递给子组件。例如:\n\nvue\n<template>\n <div>\n <ChildComponent v-model="childValue" />\n <p>父组件的值:{{ childValue }}</p>\n </div>\n</template>\n\n<script>\nimport ChildComponent from './ChildComponent.vue';\n\nexport default {\n components: {\n ChildComponent\n },\n data() {\n return {\n childValue: ''\n };\n }\n};\n</script>\n\n\n在子组件中,可以通过 props 接收父组件传递过来的值,并通过 emits 事件将修改后的值发送给父组件。例如:\n\nvue\n<template>\n <div>\n <input type="text" :value="value" @input="updateValue($event.target.value)" />\n </div>\n</template>\n\n<script>\n export default {\n props: {\n value: {\n type: String,\n required: true\n }\n },\n emits: ['update:modelValue'],\n methods: {\n updateValue(value) {\n this.$emit('update:modelValue', value);\n }\n }\n};\n</script>\n\n\n这样,当子组件中的 input 的值发生变化时,会通过 updateValue 方法将新的值发送给父组件,父组件的 childValue 也会随之更新。同时,父组件中的 childValue 的变化也会传递给子组件,子组件中的 input 的值会随之更新。\n\n注意,在子组件中,使用 emits 来声明可以触发的事件名称,这里使用了update:modelValue,这是 Vue3 中 v-model 默认的事件名称。
原文地址: https://www.cveoy.top/t/topic/pZWL 著作权归作者所有。请勿转载和采集!