Vue组件多实例下v-bind:checked绑定失效问题求助
解决多个单选框组件实例选中状态冲突的问题
嘿,我一眼就瞅出问题出在哪了——你的所有单选框都共用了同一个固定的name="radio-hashtags"!浏览器的逻辑是:只要单选框的name属性相同,就会把它们归为同一组,不管它们属于哪个组件实例。这就导致你点击任意一个实例的单选框时,浏览器会把所有同name的单选框都当成一组来处理,最终只有最后一个实例的选中状态能正常显示。
修复方案:给每个组件实例的单选框组设置唯一的name
咱们可以利用组件已经传入的cid属性,给每个实例的单选框组生成独一无二的name,这样不同实例的单选框就会被浏览器视为独立的组,互不干扰。
修改你的单选框组件模板,把固定的name="radio-hashtags"改成动态绑定的:name="'radio-hashtags-' + cid":
<template> <div class="list"> <div class="radio"> <input type="radio" :name="'radio-hashtags-' + cid" :id="'radio-hashtags-full-' + cid" value="" @change="updateHashTag" :checked="selectHashTag === ''" > <label :for="'radio-hashtags-full-' + cid">All</label> </div> <div v-for="tag in hashTags" :key="tag" class="radio"> <input type="radio" :name="'radio-hashtags-' + cid" :id="'radio-hashtags-' + tag + '-' + cid" :value="tag" @change="updateHashTag" :checked="selectHashTag === tag" > <label :for="'radio-hashtags-' + tag + '-' + cid">{{ tag }}</label> </div> </div> </template>
父组件调用注意事项
如果父组件要渲染多个实例,记得给每个实例传递不同的cid,同时绑定各自独立的selectHashTag变量,比如:
<!-- 第一个实例 --> <RadiosHashTags :hashTags="hashTagsGroup1" :selectHashTag="selectedTag1" cid="1" @updateHashTag="val => selectedTag1 = val" /> <!-- 第二个实例 --> <RadiosHashTags :hashTags="hashTagsGroup2" :selectHashTag="selectedTag2" cid="2" @updateHashTag="val => selectedTag2 = val" />
这样修改后,每个组件实例的单选框组都是独立的,点击其中一个实例的选项只会更新对应实例的选中状态,再也不会出现互相干扰的情况啦!
内容的提问来源于stack exchange,提问作者marcelo2605
相关产品推荐
相关产品推荐

