2

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 ?

2 Answers 2

1

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,
    }];
}
Sign up to request clarification or add additional context in comments.

1 Comment

I check it - this solution not working unfortunatley due to lack of __ob__:Observer and __v-for__1:Fragment in new objects in array
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.