Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue.js v-model bind to subproperty of json object

I have a JSON object called valuesRequired which is a listing of all values that I am diffing against for other purposes. What I would like to do is use this already created object to bind to the inputs. I can't seem to find a way to do it.

Here is the code, I've only provided the necessary aspects to show what I desire to do and not all of the other methods etc. The aspect I want to do is specifically v-model="valuesRequired.{{item.name}}" which in the below example would end up being v-model="valuesRequired.foo"

<ul>
    <li v-for="item in listItems" :key="item.description">
        <label :for="item.name">{{ item.description }}</label>
        <input :type="item.type" :name="item.name" v-model="valuesRequired.{{item.name}}" />
    </li>
</ul>
</fieldset>

<script>
    export default {
        data: function () {
            return {
                valuesRequired: {
                    foo: "bar"
                }
            }
        }
    }
</script>

Currently to work around this I'm dynamically adding properties to this.$data but that then requires me to map them into the valuesRequired object.

Thank you so much for your help!

like image 456
gregwhitworth Avatar asked Sep 19 '25 12:09

gregwhitworth


1 Answers

{{item.name}} is used when the default is text

Your issue is that when you do v-model='valuesRequired.{{item.name}}' this is being rendered as v-model='valuesRequired.{{My Name}}'.

Essentially, the text you pass to v-model is evaluated as JavaScript, therefore, you should use bracket notation to access valuesRequired at item.name.

What you want is the following (JSFiddle Link):

Vue.js Script Setup:

new Vue({
  el: "#app",
  data: {
    item: {
      name: 'foo'
    },
    valuesRequired: {
      foo: 'bar',
      baz: 'faz'
    }
  }
})

Vue.js HTML Template:

<div id="app">
  <input type='text' v-model='valuesRequired[item.name]' />
  <p>
    {{valuesRequired}}
  </p>
</div>
like image 133
Andria Avatar answered Sep 22 '25 00:09

Andria