Why V-model Doesn't Work With An Array And V-for Loop?
I got a custom select component, it works with a simple variable, but when used with v-for it won't work: https://jsfiddle.net/7gjkbhy3/19/
Therefore using an array of objects each of which has a property for the select value would solve the issue:
<select2v-for="item, index in samples"v-model="item.value" ></select2>
newVue({
el: '#app',
data: {
sample: 0,
samples : [{ value: 0 }, { value: 0 }, { value: 0 }]
}
})
Solution 2:
I don't like the idea of having to change the view model to resolve a framework design constraint. What if the model is to be sent to your backend via an API call? It would involve an additional step of having to mutate the model.
My solution to this was to create a Vue component that boxes the value at each array index into an object that can be referenced within it's slot. It then reacts to the data-changing by updating the array at the specified index via a watcher.
boxed-value.vue
<template><div><slotv-bind:item="boxedItem"></slot></div></template><script>exportdefault {
props: {
array: {
type: Array,
required: true
},
index: {
type: Number,
required: true
}
},
data() {
var data = {
boxedItem: {value: this.array[this.index]}
}
return data
},
created(){
},
watch: {
'boxedItem.value': function(oldValue, newValue) {
// console.log('Array item at index ' + this.index + ' value changed from ' + oldValue + ' to ' + newValue)this.array[this.index] = newValue
}
}
}
</script>
Example
<divv-for="(name, index) in primitiveValues":key="index"><boxed-value:array="primitiveValues":index="index"><templateslot-scope="{item}"><el-inputv-model="item.value"></el-input></template></boxed-value></div>
Post a Comment for "Why V-model Doesn't Work With An Array And V-for Loop?"