项目场景:
在一个v-for渲染的列表中,点击右侧的心形变为红心
问题描述
该功能实现原理是点击按钮更新数据库,通过对比用户的信息是否在数据库中存在来显示红心或白心。目前已经实现了点击心形按钮更新数据库,刷新页面后白心就会变为红心,目的是实现点击后立即变为红心。
原因分析:
由于列表的渲染是根据publishes数组,该数组的获得在mounted中执行,因此在后端返回数据后列表并不会更新数据,该列表项更不会更新
mounted() {
this.$http.get("http://localhost:8081/api/publishes").then(
(res) => {
// console.log(res);
this.publishes = res.data.data;
},
(err) => {
console.log(err);
}
);
},
解决方案:
在得到更新后的数据库数据后更新publishes数组即可
like(e) {
let id =
e.currentTarget.parentElement.parentElement.parentElement.parentElement.getAttribute(
"id"
);
this.$http
.post("http://localhost:8081/api/like", {
id: id,
account: this.account,
})
.then(
(res) => {
this.$http.get("http://localhost:8081/api/publishes").then(
(res1) => {
this.publishes = res1.data.data;
},
(err1) => {
console.log(err1);
}
);
},
(err) => {}
);
},
点击后效果如图,其余列表项也不受影响