简体   繁体   中英

Vue.js Update value of nested props sync object in component

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 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,
    }];
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM