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!
{{item.name}}
is used when the default is textYour 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With