我有一个非常简单的数组属性示例,更新时不会更改计算属性 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/