Hi i have following problem for Vue.js v1.0.28 - I have component
Vue.component('question-editor', {
template: require('./question-editor.html'),
props: ['question'],
methods: {
addChoice() {
this.question.choicesArr.push({
id: null,
body:'zzz',
icon:'',
next:null,
});
console.log(this.question.choicesArr);
},
}
});
Where ./question-editor.html
:
...
<div class="box-body">
<div class="form-group" v-for="choice of question.choicesArr">
<input v-model="choice.body" type="text" class="form-control">
</div>
</div>
<div class="box-footer">
<button @pointerdown="addChoice" type="submit" class="btn btn-primary">
Add choice
</button>
</div>
I use this component in parent component in this way:
<question-editor :question.sync="currentQuestion"></question-editor>
The problem is that when I push button "Add choice" and method addChoice()
is run, i see in console that property question.choicesArr
have new element - but view doesnt change (I don't see this new element on screen - so the v-for not "see" this new element and not refresh itself). What to do inside addChoice()
to refresh view to see new element in question.choicesArr
on screen ?
I found the solution:
addChoice() {
this.question.choicesArr.push({
id: null,
body:'zzz',
icon:'',
next:null,
});
this.question = Object.assign({}, this.question, this.question);
console.log(this.question.choicesArr);
},
The statement this.question = Object.assign({}, this.question, this.question);
will set __ob__:Observer
and __v-for__1:Fragment
to the new objects pushed to array.
I also try this.$set(this.question, 'question.choicesArr', this.question.choicesArr);
but this one set only __ob__:Observer
(not __v-for__1
) so v-for will not updated.
I read about it here: https://v2.vuejs.org/v2/guide/reactivity.html