原因 这里我们看到,打印的数组值已经发生变化,但页面没有改变。 经过测试,发现直接对数组元素进行赋值或者计算操作vue并不能监视到数组变化。 由于 JavaScript 的限制,Vue 不能检测以下变动的数组: 当你利用索引直接设置一个项时,例如:vm.items[indexOfItem] = newValue 当你修改数组的长度时,例如:vm.items.length = newLength
具体原因是因为Vue2中发布订阅模式使用的是Object.defineProperty()方法来监听数据的改变,而这个方法的缺陷就是无法监听数据变动,在Vue3中已经用Proxy代替改方法,并解决该问题。`
解决 根据vue的官方文档说明:Vue 包含一组观察数组的变异方法,所以它们将会触发视图更新。 这些方法如下:push() pop() shift() unshift() splice() sort() reverse() 所以当我们想要页面实时更新的话就必须使用以上方法。
解决办法: 【vue 中 v-for 渲染不及时 -__ 使用 $forceUpdate()】(时隔多年的更新)
async detail(item, index) {
if (item.iconType == "plus") {
let res = await getBookDetailById(item.id);
const firstBookIndexId = res.data.firstBookIndexId;
//加入书架
await addToBookShelf(item.id, firstBookIndexId)
.then((resAddToShelf) => {
if (resAddToShelf.ok) {
uni.showToast({
title: "加入书架成功",
icon: "none",
mask: true,
duration: 1000,
});
this.books[index].iconType = "minus";
this.$forceUpdate()
console.log(this.books, "触发index更新后");
} else {
this.message("error", resAddToShelf.msg);
}
})
.catch((error) => {
this.message("error", "加入书架失败" + error);
});
} else {
//移除书架
removeFromBookShelf(item.id)
.then((resRemoveToShelf) => {
if (resRemoveToShelf.ok) {
uni.showToast({
title: "移出书架成功",
icon: "none",
mask: true,
duration: 1000,
});
this.books[index].iconType = "plus";
this.$forceUpdate()
console.log(this.books, "触发index更新后");
} else {
this.message("error", resRemoveToShelf.msg);
}
})
.catch((error) => {
this.message("error", "移出书架失败" + error);
});
}
},