Search code examples
vue.jsvuex

Vue.set reactivity not working for second level child object


I have answers and each individual answer has multiple comments and each comments also has multiple child comments

...mapState({
      comments: function (state) {
        if (this.answer_id) {
          let indexIs = state.mainAnswer.answers.findIndex(answer => {
            return answer.answer_id === this.answer_id
          })
          return state.mainAnswer.answers[indexIs].comments
        }
      }
    })

I am using mapState to retrieve data from store.

Here is a screenshot how it looks

enter image description here

The screenshot depicts there is answer with the id 112 and it has 4 comments and 4th comment has child comments.

When I am trying to add a new child comment into 4th comment it does not show up instantaneously like parent comment shows up.

I have tried like but no luck

without Vue.set

state.answers[indexIs].comments[commentIndexIs].child_comments.unshift(comment)

It worked for parent comments but not for child comments

With Vue.set

Vue.set(state.answers[indexIs].comments[commentIndexIs], state.answers[indexIs].comments[commentIndexIs].child_comments, state.answers[indexIs].comments[commentIndexIs].child_comments.unshift(comment))

One thing that I want to mention is that [object Object],[object Object] in screenshot is being showed when i am using Vue.set, if anybody can explain this that would be great


Solution

  • Vue itself is reactive to unshift(). But your object chain is so long, part of them may not be set reactive.

    I have try this data:

    export default {
            data(){return{
                a:[],
                b:[],
                c:[],
                d:['apple','banana','car'],}},
    

    view:

    <div v-for="bs in a.key">
        <div v-for="cs in bs">
            <div v-for="ds in cs">{{ds}}</div>    
        </div>        
    </div>
    

    this method gives reactivity:

    mounted(){
                Vue.set(this.a, "key", this.b);
                this.b.push(this.c);
                this.c.push(this.d);
                this.d.unshift('zoo');
    }
    

    but this is not giving reactivity:

     mounted() {
                this.a.key = this.b;
                this.b[0] = this.c;
                this.c[0] = this.d;
                this.d.unshift('zoo');
    }
    

    please take a look which part of the object chain in your code is set by object.key = bla, or which array element is set by array[key] = blabla, because those methods are not reactive.

    Also, unshift() return length instead of new element value, so your usage does not match the args of defined Vue.set(object,key,value)