I want to pass an object value ( product.id
) to a v-model
of an input. The problem is when I do that, I get a string "product.id" not product.id
as an object. How can I convert the string? Or is this the wrong way?
I tried JSON.parse, but it was not working.
<template>
<div>
<div v-for="field in fields" :key="field.id">
<label>{{ field.name }}</label>
<input type="text" v-model="field.model" />
</div>
</div>
</template>
<script>
export default{
data() {
return {
product: {
id: '',
name: '',
price: ''
},
fields: [
{
name: 'Name 1',
model: 'product.id',
},
{
name: 'Name 2',
model: 'product.name',
},
{
name: 'Name 3',
model: 'product.price',
}
]
}
}
}
</script>
Not sure why you wanted to do this, but since v-model
only takes an object, one way I can think of is to reassign the field.model
s with the evaluated versions as object. Not necessarily a good approach but works:
new Vue({ el: '#app', data() { return { product: { id: '112233', name: 'Random name', price: '$34.5' }, fields: [{ name: 'Name 1', model: 'product.id', }, { name: 'Name 2', model: 'product.name', }, { name: 'Name 3', model: 'product.price', } ] } }, computed: { specialFields() { return this.fields.map(item => Object.assign(item, { model: eval(`this.${item.model}`) })); } } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <div v-for="field in specialFields" :key="field.id"> <label>{{ field.name }}</label> <input type="text" v-model.trim="field.model" /> </div> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.