[Vuejs]-Bind data to vue model dynamically in component

2👍

Couple of things you might need to correct:

First, the data property must be a function rather than an object. This allows every instance to get data recomputed every time it is being created, see:

var vm = new Vue({
  el: "#app",
  data() {
    return {
      currencies: ['USD', 'BTC'],
      values: {
        'BTC': 'BTC Value',
        'USD': 'USD Value',
      },
    };
  }
});

Second, <conversion-row> doesn’t have values property bound. Here’s what you can do:

<div id="app">
  <li v-for="currency in currencies">
    <conversion-row :currency="currency" :values="values"></conversion-row>
  </li>
</div>

Last, the component should always aim for one root element (wrapper) and then you can nest as many children inside as you want. What’s more, instead of using v-model, you can bind value which is the proper way to pass a value to an input (one-way data binding), check the following:

Vue.component('conversion-row', {
  props: ['currency', 'values'],
  template: '<div>{{currency}}:<input type="text" :value="values[currency]"></div>'
});

There’s more improvements you could possibly make here like re-thinking if you need to pass values as well as currency to the conversion-row but I’m pretty sure you’ll figure it out later on.

All that above will make your code run and execute properly, here’s the working example (fork of yours):

Does this help?

Not sure what you’re aiming for in terms of using v-model, but here’s an example of working v-model (based on your example):

Vue.component('conversion-row', {
  props: ['currency', 'values'],
  template: '<div>{{currency}}:<input type="text" v-model="values[currency]"></div>'
});

And the corresponding template:

<div id="app">  
  <p><strong>USD Value:</strong> {{ values.USD }}</p>
  <p><strong>BTC Value:</strong> {{ values.BTC }}</p>

  <br>

  <li v-for="currency in currencies">
    <conversion-row :currency="currency" :values="values"></conversion-row>
  </li>
</div>

You can find it under the following URL:

Leave a comment