I am trying to implement an associated array bined with accessing the property within the value, the key is based on the value of the campaign object.
<li v-for="campaign in campaigns">
<input type="text" v-model="configuration[campaign._id].value"> {{ configuration[campaign._id].value }}
</li>
/
Am I missing anything, it feels really bugged out. About exactly the same happens when trying to do this in VueJS 1, both times it's not throwing any errors.
I am trying to implement an associated array bined with accessing the property within the value, the key is based on the value of the campaign object.
<li v-for="campaign in campaigns">
<input type="text" v-model="configuration[campaign._id].value"> {{ configuration[campaign._id].value }}
</li>
https://jsfiddle/4yc3bujt/1/
Am I missing anything, it feels really bugged out. About exactly the same happens when trying to do this in VueJS 1, both times it's not throwing any errors.
Share Improve this question edited Feb 7, 2017 at 2:14 Saurabh 73.6k44 gold badges190 silver badges251 bronze badges asked Feb 6, 2017 at 20:49 Maarten de GraafMaarten de Graaf 5262 gold badges5 silver badges21 bronze badges2 Answers
Reset to default 18This is happening due to caveats of reactivity in vue.js
. You have just defined configuration: {}
initially in data, so configuration[key]
are not reactive. To make these reactive, you have to use this.$set:
Set a property on an object. If the object is reactive, ensure the property is created as a reactive property and trigger view updates. This is primarily used to get around the limitation that Vue cannot detect property additions.
use like following:
this.campaigns.forEach((campaign) => {
var id = campaign._id;
this.$set(this.configuration, id, {'value': 'default value'})
})
var app = new Vue({
el: '#app',
data: {
campaigns: [],
configuration: {}
},
mounted: function() {
this.campaigns = [{
_id: 'abcdefg'
}, {
_id: 'kejwkfe'
}, {
_id: 'iruwiwe'
}, {
_id: 'reiwehb'
}];
this.campaigns.forEach((campaign) => {
var id = campaign._id;
this.$set(this.configuration, id, {'value': 'default value'})
})
}
})
<script src="https://vuejs/js/vue.js"></script>
<div id="app">
<ul>
<li v-for="campaign in campaigns">
<input type="text" v-model="configuration[campaign._id].value" />
{{ configuration[campaign._id].value }}
</li>
</ul>
</div>
Properties with reactivity must be in a Vue instance which is created by Vue constructor.
It ensures that properties are reactive and trigger view updates, i.e., they are initialed with Object.defineProperty
and MutationObserver
underlyingly.
So, use Vue.set
to add new properties, and delete by Vue.delete
.
View more info - Reactivity in Depth