vue中watch执行先于computed,在watch中有调用computed后的对象,该怎么改呢?
比如,我切换图片时,触发以下method:
setActiveImage(image) { for (const imageItem of this.imageList) {
imageItem.active = false;
}
image.active = true;
// 此处修改了watch的值
this.test = "xxx";
}
这里自动切换到当前图片对象
computed: { activeImage() {
return this.imageList.find((image) => {
return image.active;
});
},
}
最后在watch时使用到了computed后的对象,但是computed是在watch之后执行的,activeImage数据就不对,有没有什么办法解决?
watch: { "test": {
handler() {
// 这里使用到了computed后的对象,这里的数据不正确
this.dosomething(this.activeImage);
},
deep: true
}
}
回答:
Vue.set :
setActiveImage(image) { this.imageList.forEach((imageItem, index) => {
this.$set(this.imageList, index, { ...imageItem, active: false });
});
this.$set(this.imageList, this.imageList.indexOf(image), { ...image, active: true });
}
或者直接调用:
setActiveImage(image) { for (const imageItem of this.imageList) {
imageItem.active = false;
}
image.active = true;
// 在这里直接调用
this.$nextTick(() => {
this.dosomething(this.activeImage);
});
}
setActiveImage(image) {
for (const imageItem of this.imageList) {
imageItem.active = false;
}
image.active = true;
// 在这里直接调用
this.$nextTick(() => {
this.dosomething(this.activeImage);
});
}
以上是 vue中watch执行先于computed,在watch中有调用computed后的对象,该怎么改呢? 的全部内容, 来源链接: utcz.com/p/935101.html