Reputation: 92627
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 ?
Upvotes: 2
Views: 1853
Reputation: 73649
I guess vue 1.x, does not detect changes in array as it does in 2.x, you can do following to let vue know that array has been changed with the help of spread operator.
addChoice() {
this.question.choicesArr= [...this.question.choicesArr, {
id: null,
body:'zzz',
icon:'',
next:null,
}];
}
Upvotes: 1
Reputation: 92627
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
Upvotes: 0