javascript - 数组不更新的 Vue 计算属性

标签 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"});

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>

我希望,因为 mycomputed 基于 myarray,所以对 myarray 的任何更改都会导致 computed 更新。我错过了什么?

我已经更新了我的示例 - 带有 secondprop 的 mycomputed2 已正确更新(对于数字)。但 myarray 作为 Prop 不是。

最佳答案

Prop 不是响应式(Reactive)的。使用数据:

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"});

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

关于javascript - 数组不更新的 Vue 计算属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51455069/

相关文章:

javascript - 如何更新 Nuxt.js 到最新版本

javascript - 我可以等待 fs.readdir 但我不知道为什么

javascript - 在单文件组件方法中使用 vue 样式组件

unit-testing - 如何模拟 this.$refs.form.resetValidation()?

javascript - getJSON 未获取数据

javascript - 将鼠标悬停在非父级/非同级 div 上时,div 背景图像会发生变化

javascript - 在函数内设置全局变量

javascript - 如何更新 Vue 数据以反射(reflect)用户输入对 HTML 所做的更改

javascript - 如何在 Three.js 中创建鸡蛋网格?

javascript - 使用 JS .match() 从字符串中提取数字,然后使用结果来测试相等性