带有未更新数组的Vue计算属性

maq*_*que 6 javascript vue.js

我有一个非常简单的数组属性案例,更新后不会使计算属性更改 jsfidle 链接: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"});
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

我希望,由于 mycomputed 是基于 myarray,因此对 myarray 的任何更改都将导致计算更新。我错过了什么?

我已经更新了我的例子 - mycomputed2 与 secondprop 正确更新(对于数字)。但是 myarray 作为道具没有。

Vla*_*rin 6

道具不是反应式的。使用数据:

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"});
Run Code Online (Sandbox Code Playgroud)

我将 props 数组复制到数据中。