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

Vue.js如何通过两个动态变量实现二维数组的动态v-model绑定?

解决Vue中二维动态v-model绑定失效问题

你遇到的问题根源是初始化的数据类型错误:你想要的是嵌套对象结构,但初始把shirt_count设成了数组。数组只能用数字索引,没法用brand_a、red这类字符串作为键名,所以shirt_count[brand][color]的绑定自然不生效。

正确的实现步骤:

  1. 把shirt_count初始化为空对象,而非数组,这样才能用字符串作为键名存储品牌和颜色对应的计数。
  2. 提前初始化嵌套结构:在组件挂载或props更新时,为每个品牌创建对应的颜色对象,避免直接访问未定义的属性导致Vue响应式失效。
  3. 保持模板中的v-model绑定写法不变,确保结构匹配。

完整代码示例:

<template>  
  <div v-for="brand in brands" :key="brand">
    <div v-for="color in colors" :key="color">
      <input type="text" v-model="shirt_count[brand][color]" />
    </div>
  </div>
</template>

<script>
export default {
  props: ['brands', 'colors'],
  data() {
    return {
      shirt_count: {} // 初始化为空对象
    }
  },
  mounted() {
    this.initShirtCount()
  },
  watch: {
    // 监听props变化,重新初始化结构
    brands: {
      handler() {
        this.initShirtCount()
      },
      deep: true
    },
    colors: {
      handler() {
        this.initShirtCount()
      },
      deep: true
    }
  },
  methods: {
    initShirtCount() {
      this.brands.forEach(brand => {
        // 如果品牌不存在,创建对应的颜色对象
        if (!this.shirt_count[brand]) {
          this.shirt_count[brand] = {}
        }
        // 为每个颜色初始化默认值(比如空字符串或0)
        this.colors.forEach(color => {
          if (this.shirt_count[brand][color] === undefined) {
            this.shirt_count[brand][color] = ''
          }
        })
      })
    }
  }
}
</script>

补充说明:

  • 添加:key属性是Vue列表渲染的最佳实践,避免DOM复用导致的异常。
  • 监听brands和colors的变化,确保当props更新时,shirt_count的结构能同步更新,保持绑定有效。
  • 初始化颜色计数为''(适配输入框的文本类型),如果需要数字类型,可以改成0,同时给input加上type="number"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 21:20:24