Vue 3组件数据绑定失效:输入未同步更新{{test}}
问题分析与修复方案
你的代码存在两个关键问题导致{{test}}无法更新:
- 根组件未声明响应式数据
test:v-model绑定的变量必须在Vue根实例中定义为响应式数据,否则Vue无法追踪其变化并更新视图。 - 输入事件选择不合理:使用
keyup事件会遗漏部分输入场景(比如鼠标右键粘贴内容),无法实时响应输入框的内容变化,应改用input事件。
修复后的完整代码如下:
<html> <body> <Component v-model="test"></Component> {{test}} <script type="module"> import {createApp} from './node_modules/vue/dist/vue.esm-browser.prod.js'; const Component = { props: { modelValue: String, }, emits: [ 'update:modelValue', ], template: `<input @input="updateValue">`, methods: { updateValue(event) { this.$emit('update:modelValue', event.target.value); }, }, }; const app = createApp({ data() { return { test: '' } } }); app.component('Component', Component); app.mount('body'); </script> </body> </html>
内容的提问来源于stack exchange,提问作者László Monda
相关产品推荐
相关产品推荐

