8

I have this very simple case of an array property, which when updated doesn't make a computed property change jsfidle link: https://jsfiddle.net/fx1v4ze6/30/

Vue.component('test', {
 data: function() { 
     return {
        arr: this.myarray.slice()
     }
  },
      props:['myarray','secondprop'],
      template:'#arraybug',
      methods:{
        add:function(){
          this.myarray.push(1);
          this.secondprop+=1;
          this.arr.push(1);
        }
      },
      computed:{
        mycomputed: function(){
            return this.arr.length;
        },
        mycomputed2: function(){
            return this.secondprop;
        },
        mycomputed3: function(){
            return this.myarray.length;
        },
      }
     });

    var test = new Vue({
      el:"#test"});

HTML:

    <div id="test">
  <test :myarray="[1,2,3]" :secondprop="1"></test>
</div>
<template id="arraybug">
  <div >
    <button v-on:click="add()">
      click
    </button>
    {{mycomputed}} - {{mycomputed2}} - {{mycomputed3}}
  </div>
</template>

I would expect, since mycomputed is based on myarray, that any change to myarray will cause computed to update. What I have missed?

I've updated my exaple - mycomputed2 with secondprop is updated properly (for number). But myarray as a prop not.

2 Answers 2

6

Props are not Reactive. Use data:

Vue.component('test', {
 props:['myarray'],
  data: function() { 
     return {
        arr: this.myarray.slice()
     }
  },
  template:'#arraybug',
  methods:{
    add:function(){

      this.arr.push(1);
    }
  },
  computed:{
    mycomputed: function(){
        let newLen = this.arr.length;
        return newLen;
    }
  }
 });

var test = new Vue({
  el:"#test"});

I'm copied props array to data.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thank you. Your example works, but please take a look at my edited changes. "secondprop" which is prop, is updated (number value) so why array doesn't behave same way?
It is not recommended to do so. Look at the console output VM38 vue.js:485 [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "secondprop"
1

Vue can't detect the internal change of an array as mentioned here: https://v2.vuejs.org/v2/guide/reactivity.html

Alternatively, if an array is used as a prop, in the component the prop is passed to, you can add a data field, and use methods (instead of computed) and watchers as shown in the example here: https://v2.vuejs.org/v2/guide/computed.html#Watchers

1 Comment

This is no longer true in vue3: [vuejs.org/guide/essentials/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.