Vue v-for循环中@change事件仅传递首个项ID的问题如何解决?
问题原因
该问题本质是HTML元素ID全局重复导致的label关联错误:
- v-for循环中给所有单选框设置了固定ID
accept和revoke,但HTML规范要求页面内元素ID必须全局唯一 - label的
for属性只会匹配页面上第一个对应ID的<input>元素,所以无论点击哪一行的Yes/No文字,实际触发的都是第一行单选框的change事件,自然每次拿到的都是第一个项的ID
解决方案
把单选框的ID和对应label的for属性,改成和当前行m.id绑定的动态值,保证全局唯一即可,修改后代码如下:
<tr v-for="(m, i) in list.accounts" :key="i"> <td class="border-top-0"> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" name="accept_revoke" :id="`accept_${m.id}`" value="1" :checked="list.acceptRevoke[m.id] == 1" @change="dialogConfirm(m.id)" /> <label class="custom-control-label" :for="`accept_${m.id}`">Yes ---{{m.id}}</label> </div> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" name="accept_revoke" :id="`revoke_${m.id}`" value="0" :checked="list.acceptRevoke[m.id] == 0" @change="dialogConfirm(m.id)" /> <label class="custom-control-label" :for="`revoke_${m.id}`">No---{{m.id}}</label> </div> </td> </tr>
补充说明
如果需要每行的Yes/No单选是独立分组(也就是可以每行单独选Yes/No,而不是全页面只能选一个选项),还需要把单选框的name属性也改成和m.id绑定的动态值::name="accept_revoke_${m.id}"
内容的提问来源于stack exchange,提问作者Ravn
相关产品推荐
相关产品推荐

