Vue.js中如何在使用:is绑定的动态组件内使用输入框
Hey there! As a fellow Vue enthusiast, let's work through this issue together. I see you're trying to edit data rendered via v-for inside a dynamic component using :is, and you suspect that input event line is the problem—you're absolutely right!
What's Wrong with That Input Emit?
The line v-on:input="$emit('input', $event.target.info.name)" is trying to access info.name from the input element ($event.target), but input elements don't have an info property attached to them. That means you're emitting undefined instead of the actual input value, which is why your updates aren't working.
Step-by-Step Fix
Let's break down how to get this working properly:
Correct the Input Event Emit
First, change the input event to send the actual value of the input field. Replace that line with:v-on:input="$emit('input', $event.target.value)"Or even better, use Vue's
v-modelsyntax sugar for cleaner code. If your dynamic component accepts avalueprop, you can bind the input directly:<input v-model="localValue" />Then in the component's script, add a watcher to sync changes back to the parent:
props: ['value'], data() { return { localValue: this.value } }, watch: { localValue(newVal) { this.$emit('input', newVal) } }Ensure Proper Data Binding to Dynamic Components
Since you're usingv-for, make sure each dynamic component is bound to a unique data item. In your parent component, pass the specificinfoitem as a prop and usev-modelto sync updates back to your parent data:<component :is="currentComponent" v-for="(item, index) in items" :key="index" v-model="item.name" :info="item" />Toggle Edit Mode Cleanly
When you click the edit button, switch thecurrentComponentto your edit-enabled component, and ensure it receives the correct data to modify. Double-check that your edit component accepts the necessary props to display and update the data.
Quick Recap
- Your original emit targeted a non-existent property on the input element—fix this to send the actual input value.
- Use
v-model(either directly or with custom emits) to keep parent and child component data in sync. - Ensure each dynamic component in your
v-forloop is bound to a unique data item with a properkey.
That should get your edit functionality working smoothly! Let me know if you run into any other snags as you keep learning Vue—we've all been there.
内容的提问来源于stack exchange,提问作者Taylor

