【问题标题】:Vue JS taking input dynamically inside v-forVue JS 在 v-for 中动态获取输入
【发布时间】:2022-11-13 18:12:44
【问题描述】:

嗨,我正在尝试以这种方式输入:

itemPrices: [{regionId: "A", price: "200"},{regionId: "B", price: "100"}]

当用户按下添加按钮时,会添加新的输入字段。
为此,我在 vue 应用程序数据中采用了一个空数组 => itemPrices: [],
现在在表格元素里面我有这个代码:

<vs-tr v-for="n in num" v-bind:key="n">
  <vs-td
    ><vs-input
      v-model="itemPrices[n].regionId"
      placeholder="Region Name"
    /></vs-td>
    <vs-td>
      <vs-input
        placeholder="price"
        v-model="itemPrices[n].price"
      />
    </vs-td>
  </vs-tr>

这里的“num”只是一个整数,它决定应该有多少行。但这不起作用......这个任务的可能解决方案是什么?

【问题讨论】:

    标签: javascript html vue.js vuejs3 v-for


    【解决方案1】:

    如果我理解正确,您将num 设置为itemPrices 数组长度:

    new Vue({
      el: '#demo',
      data() {
        return {
          itemPrices: []
        }
      },
      computed: {
        num() {
          return this.itemPrices.length
        }
      },
      methods: {
        addItem() {
          this.itemPrices = [...this.itemPrices, {regionId: "", price: ""}]
        }
      }
    })
    <link href="https://unpkg.com/vuesax@4.0.1-alpha.16/dist/vuesax.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <script src="https://unpkg.com/vuesax@4.0.1-alpha.16/dist/vuesax.min.js"></script>
    <div id="demo">
      <vs-button @click="addItem">add</vs-button>
      <vs-tr v-for="(n, i) in num" :key="n">
        <vs-td>
          <vs-input
            v-model="itemPrices[i].regionId"
            placeholder="Region Name"
          />
        </vs-td>
        <vs-td>
          <vs-input
            placeholder="price"
            v-model="itemPrices[i].price"
          />
        </vs-td>
      </vs-tr>
    </div>

    【讨论】:

      【解决方案2】:

      如果您确定“num”是一个填充数组,我认为您可以使用以下代码:

      <vs-tr v-for="n in num" v-bind:key="n">
                  <vs-td
                    ><vs-input
                      v-model="n.regionId"
                      placeholder="Region Name"
                  /></vs-td>
                  <vs-td>
                    <vs-input
                      placeholder="price"
                      v-model="n.price"
                    />
                  </vs-td>
                </vs-tr>
      

      因为 n 是数组中每个实例的表示。

      虽然,您也应该提供 JS 代码。通过这种方式,这里的人们可以更好地了解正在发生的事情。例如,我看不到“num”是什么样的。

      【讨论】:

      • num 只是一个数字......它决定了需要有多少行
      • 那你为什么不直接在你的数组上使用 v-for 呢?
      • v-for=“数组中的(项目,索引)”:key=“索引”
      • 因为它是一个空数组,我需要动态地用输入填充它。
      • 好的。但是,如果数组 (itemPrices: []) 是一个空数组,并且您正在尝试对数据进行 v 建模,例如itemPrices.regionId 它将确定。因为你的空数组中没有属性 regionId ,对吗?
      猜你喜欢
      • 2019-04-30
      • 1970-01-01
      • 2021-12-18
      • 2020-10-25
      • 1970-01-01
      • 2021-05-28
      • 2020-05-15
      • 1970-01-01
      • 2018-11-16
      相关资源
      最近更新 更多