带有 v-for 的动态 v-model [英] Dynamic v-model with v-for

查看:39
本文介绍了带有 v-for 的动态 v-model的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 v-for 循环,它将吐出多行输入,我想将每一行动态保存到数组对象中.

I have a v-for loop that is going to spit out multiple rows of inputs that I would like to save each separate row to an array object dynamically.

v-for:

<table class="table m-0">
  <tbody>
    <tr v-for="fund in defaultFunds">
      <td>
        {{fund.name}}
        <b-input v-model="newEntries[fund.id]['id']" 
                 :value="fund.id" 
                 name="entryFund" 
                 type="text" 
                 class="d-none" 
                 :key="fund.id" />
      </td>
      <td>
        <b-input v-model="newEntries[fund.id]['amount']" 
                 name="newFundAmount" 
                 id="newFundAmount" 
                 type="text" 
                 placeholder="Amount" 
                 :key="fund.id"/>
      </td>
    </tr>
  </tbody>
</table>

想要的数组(以输入2行为例):

Desired array (using example of entering 2 rows):

newEntries: [
  { id: '1', amount: '50.00' },
  { id: '2', amount: '123.45' }
],

默认情况下,我将 newEntries 加载为空数组.我不知道如何使用 v-for 获得我想要的那种数组对象.使用上面的代码,我最终得到了这个:

I load newEntries as an empty array by default. I don't know how to get the kind of array object I want with v-for. With the above code I end up with this:

newEntries: [null, '50.00', '123.45']

我做错了什么?

推荐答案

你想要这样的东西吗:

https://jsfiddle.net/e6L5seec/

<div id="app">
   newEntries: {{ newEntries }}
   <table>
      <tr v-for="(fund, index) in defaultFunds">
         <td>{{ fund.name }}</td>
         <td>
            <input    v-model="newEntries[index].id"
               name="entryFund"
               :value="fund.id"
               type="text"  />
         </td>
         <td>
            <input  v-model="newEntries[index].amount"
               name="entryFund" 
               type="text"  />
         </td>
      </tr>
   </table>
</div>

new Vue({
  el: "#app",
  data: function() {
    return {
          defaultFunds: [
      {
        id: 0,
        name: 'fund 0'
      },
      {
        id: 1,
        name: 'fund 1'
      }
    ],
    newEntries: [{}, {}]
    }
  },
  methods: {
  }
});

这篇关于带有 v-for 的动态 v-model的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆