[英]Vue computed property with an array not updating
我有一个非常简单的数组属性案例,更新时不会使计算属性更改 jsfiddle 链接: 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 的任何更改都会导致计算更新。 我错过了什么?
我已经更新了我的示例-带有 secondprop 的 mycomputed2 已正确更新(对于数字)。 但 myarray 作为道具不行。
道具不是反应性的。 使用数据:
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"});
我将道具数组复制到数据中。
Vue 无法检测到此处提到的数组的内部变化: https ://v2.vuejs.org/v2/guide/reactivity.html
或者,如果将数组用作道具,则在道具传递到的组件中,您可以添加数据字段,并使用方法(而不是计算)和观察者,如此处示例所示: https://v2. vuejs.org/v2/guide/computed.html#Watchers
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.