【发布时间】:2026-01-06 14:35:02
【问题描述】:
我有一个表格行,每个行都包含一个选择。希望当“选择”选项更改时,更新父级(包含该表)的数据。
<tbody>
<tr is="itemComponent"
v-for="(item, index) in items"
v-bind:index="index"
v-bind:item="item"
v-bind:item-attribute.sync="item.attribute"
</tr>
</tbody>
然后在 itemComponent 中(接收 item-attribute 作为道具):
<td>
<select
v-bind:value="item-attribute"
v-on:change="$emit('update:item-attribute', $event.target.value)
>
<option v-bind:value="true">Yes</option>
<option v-bind:value="false">No</option>
</select>
</td>
使用 Vue 的 Chrome 扩展程序,我可以看到 <select> 对 item.attribute 有反应(如果我手动更改它,则选择中的选定选项会更改),并且它还会触发 'update:item-attribute ' 更改时的事件,但它不会更新父级的 item.item-attribute 值。
由于 .sync 只是 v-on:update:item-attribute 的糖,如果我不想使用 .sync,我需要在父组件上写这样的东西:
<tbody>
<tr is="itemComponent"
v-for="(item, index) in items"
v-bind:index="index"
v-bind:item="item"
v-bind:item-attribute="item.attribute"
v-on:update:item-attribute="updateItemAttribute"
</tr>
</tbody>
methods: {
updateItemAttribute: function(index,attributeValue) {
this.items[index].attribute = attributeValue;
}
}
并且,在子组件上,将 select 中的发出调用更改为(考虑索引为:
v-on:change="$emit('update:item-attribute', index, $event.target.value)
.sync 不应该帮助我避免编写所有这些代码吗?我找不到任何提及它与 v-for 一起使用的内容。
【问题讨论】:
-
我可以在这个 jsfiddle jsfiddle.net/jacobgoh101/g5bv0esd/1 中重现这个问题。我还在github.com/vuejs/vue/issues/8373 中提交了一个新的 Vue 问题
-
答案是事件名称应该是camelCase。不是烤肉串。
$emit('update:itemAttribute',...)。见github.com/vuejs/vue/issues/8373
标签: vue.js