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
    }
}
阅读 858
1 个回答

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);
    });
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题