Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic v-model with 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>

Desired array (using example of entering 2 rows):

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

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']

What am I doing wrong?

like image 873
Jason Ayer Avatar asked Mar 06 '23 03:03

Jason Ayer


1 Answers

Do you want something like this:

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: {
  }
});
like image 141
ittus Avatar answered Mar 21 '23 11:03

ittus