<div class="layui-tab-content layui-row layui-col-space30"> <div class="layui-col-xs3" v-for="(collect, index) in collectBook" :key="index"> <div class="goods"> <a :href="'detail?id='+collect.bookId"> <img :src="'/BookShopSystem_war/' + collect.image1"> </a> <p>{{ collect.bookName }}</p> <p class="price">¥{{ collect.bookPrice }}</p> <button @click="delCollect()"> <span class="del">×</span> </button> </div> </div> </div> new Vue({ el: "#app", data: { userId: '', collectBook: [] }, mounted() { var _this = this; axios.get('/BookShopSystem_war/getUserId') .then((response) => { this.userId = response.data; var userId = this.userId; // 将userId赋值给一个变量 axios({ method: 'get', url: 'http://localhost:8080/BookShopSystem_war/getCollectBook/' + userId }).then(function (result) { var code = result.data.code; var data = result.data.data; if (code == 200) { _this.collectBook = data; } console.log(data) }) }) .catch((error) => { console.log(error); }); }, methods: { delCollect() { var _this = this; axios({ method: "delete", url: "http://localhost:8080/BookShopSystem_war/deleteCollect", data: { userId: _this.userId, bookId: _this.collectBook.bookId } }).then(resp => { alert("取消收藏"); }) } }该取消收藏方法有错,给出原因并纠正
时间: 2024-02-15 17:26:58 浏览: 268
layui-steps
在 `delCollect()` 方法中,`_this.collectBook.bookId` 是错误的,因为 `collectBook` 是一个数组,而不是一个单独的对象。另外,通过 `v-for="(collect, index) in collectBook"` 循环遍历 `collectBook` 数组,所以应该在 `delCollect()` 方法中传递 `collect.bookId` 作为参数,以便正确删除相应的收藏。以下是修改后的代码:
```
delCollect(bookId) {
var _this = this;
axios({
method: "delete",
url: "http://localhost:8080/BookShopSystem_war/deleteCollect",
data: {
userId: _this.userId,
bookId: bookId
}
}).then(resp => {
alert("取消收藏");
// 从 collectBook 数组中移除被删除的收藏
_this.collectBook = _this.collectBook.filter(collect => collect.bookId !== bookId);
});
}
```
在模板中,需要将 `delCollect()` 方法调用中的参数改为 `collect.bookId`:
```
<button @click="delCollect(collect.bookId)">
```
阅读全文