【发布时间】:2021-10-24 03:14:29
【问题描述】:
我正在使用 localStorage 创建购物车
然后我从 ProductCard.vue
产品.vue
<template>
<button
type="button"
class="product__btn add_to_cart_btn"
@click.prevent="addToCart(product)"
>
Add to cart
</button>
</template>
<script>
import { EventBus } from "../app";
export default {
name: "ProductCard",
methods: {
addToCart(product) {
this.addCartLoading = true
setTimeout(() => {
this.addCartLoading = false
EventBus.$emit('addToCart', product)
}, 300)
},
}
}
</script>
我在App.vue 中看到了这个事件,如下所示
App.vue
<script>
export default {
name: "App",
data() {
return {
shoppingCart: [],
}
},
created() {
EventBus.$on('addToCart', this.setCartContents)
},
methods: {
setCartContents(product) {
let productExistOnCart = this.shoppingCart.find(cart => cart.id === product.id)
if (product !== undefined && product !== null) {
this.shoppingCart.push({
id: product.id,
name: product.name,
qty: 1,
price: product.price,
options: {
old_price: product.old_price,
image: product.image,
}
})
localStorage.setItem('shoppingCart', JSON.stringify(this.shoppingCart))
}
},
}
}
</script>
然后我来到我的CartItemsWrapper.vue 组件,它显示了我添加的所有项目,并通过v-for 循环将它们显示在列表中 CartItemsWrapper.vue 问题在这里,我删除了该项目但是并且它从我的this.shoppingCart 和localstorage 中删除,但是当我重新添加一些产品而不刷新页面localstorage 时,所有删除的值都会再次出现在我的cart 中,如果我刷新洞页面,它并没有完全删除在购物车中添加一些东西然后好吧,我怎样才能在不刷新页面的情况下完全删除项目。?请任何人帮助我。
CartItemsWrapper.vue
<button type="button" class="remove-btn" @click.prevent="removeCart(cart)">
Remove
</button>
<script>
export default {
name: "CartItemsWrapper",
data() {
return {
shoppingCart: [],
}
},
methods: {
removeCart(cart) {
let cartItems = JSON.parse(localStorage.getItem('shoppingCart'))
for (let i = 0; i < cartItems.length; i++) {
if(cartItems[i].id == cart.id) {
cartItems.splice(i, 1);
break;
}
}
localStorage.setItem("shoppingCart", JSON.stringify(cartItems))
this.refreshCart()
},
}
}
here is gif你可以看到
【问题讨论】:
-
在 removeCart 中,您不会从 App.vue 中的 this.shoppingCart 中删除项目,因此在添加另一个时它不会添加它,天哪,您应该真的使用 vuex,然后您就不需要大多数父/子 getter/setter/eventbus 膨胀
-
我没有看到您在 App.vue 文件中处理 removeCart 和 addToCart 的代码。使用这样的事件总线来更改数据的替代方法是通过
provide/inject向下传递数据,然后您可以直接在您需要的组件中访问数据,而无需支撑钻或必须传递事件(又名反向螺旋钻)。你也可以在这里使用 Vuex,但我认为对于这么小的连接来说这可能有点矫枉过正。 -
@brff19 我忘记在我更新的
App.vue问题中添加这一行created() { EventBus.$on('addToCart', this.setCartContents) },,然后我还从CartItemsWrapper.vue触发了一个事件removeCart。?
标签: vue.js vuejs2 local-storage