You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue渲染列表复选框选中的attribute_id无法在绑定数组中展示问题

错误点梳理

核心错误

你使用的Field是VeeValidate库的专用表单组件,它默认绑定VeeValidate内置的表单状态,不会直接响应你自定义的selectedAttributes数组变量,这是绑定失效的核心原因。

次要错误

  • label标签的for属性没有加冒号做动态绑定,当前是固定字符串"attributes.attribute_id",无法和复选框的动态id匹配,会导致点击label无法选中对应复选框。
  • ul循环的key绑定了category.name,如果存在分类名重复的情况会导致渲染异常,建议用唯一的分类id作为key。

修复方案

方案1:直接使用原生input标签(最简便)

不需要用到VeeValidate的校验能力的话,直接替换为原生复选框即可正常绑定数组:

<!-- 选中结果展示 -->
<pre>{{ JSON.stringify(selectedAttributes, null, 2) }}</pre>

<ul
  class="list-unstyled"
  v-for="category in categories"
  :key="category.category_id"
>
  <strong>{{ category.category_name }}</strong>
  <li
    v-for="attributes in category.attributes"
    :key="attributes.attribute_id"
  >
    <input
      type="checkbox"
      class="form-check-input"
      v-model="selectedAttributes"
      :id="attributes.attribute_id"
      :value="attributes.attribute_id"
    />
    <label class="form-check-label" :for="attributes.attribute_id">
      {{ attributes.attribute_name }}
    </label>
  </li>
</ul>

<script>
export default {
  data() {
    return {
      selectedAttributes: [],
      // 其他业务变量
    };
  },
}
</script>

方案2:保留Field组件手动处理绑定

如果需要用到VeeValidate的校验能力,可以手动控制选中状态和数组更新:

<Field
  as="input"
  name="attribute"
  type="checkbox"
  class="form-check-input"
  :id="attributes.attribute_id"
  :value="attributes.attribute_id"
  :checked="selectedAttributes.includes(attributes.attribute_id)"
  @change="(e) => {
    const targetId = attributes.attribute_id
    if (e.target.checked) {
      !selectedAttributes.includes(targetId) && selectedAttributes.push(targetId)
    } else {
      selectedAttributes = selectedAttributes.filter(id => id !== targetId)
    }
  }"
/>

修改后勾选复选框即可正常将对应attribute_id存入selectedAttributes数组并实时展示。


内容的提问来源于stack exchange,提问作者roxena

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 20:45:04