简体   繁体   中英

Vue computed property with an array not updating

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.

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.

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

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