Shopify购物车更新不适用于axios [英] Shopify cart update not working with axios
问题描述
我试图从购物车中永久删除产品,但是我创建的功能仅从DOM中删除数据,并且在浏览器刷新后会重新出现.这是我到目前为止所做的.
I am trying to permanently remove product items from my cart, but the function i created only only removes the data from the DOM and upon browser resfresh, reappears. Here is what i have done so far.
cart.liquid文件中具有JS单击功能的HTML
HTML with JS click function in the cart.liquid file
<a @click="removeFromCart(item)" class="product-remove">remove</a>
我的CartForm.js文件中的removeFromCart函数
removeFromCart function in my CartForm.js file
removeFromCart(item){
let productInfo = this.cart.items.reduce(
(accumulator, target) => ({ ...accumulator, [target.variant_id]: target.quantity}),
{});
const myJSON = JSON.stringify(productInfo);
axios.post('/cart/update.js', { updates: productInfo })
.then((res) => {
this.cart.items.splice(this.cart.items.indexOf(productInfo), 1);
})
.catch((error) => {
new Noty({
type: 'error',
timeout: 3000,
layout: 'topRight',
text: 'Cart not updated'
}).show();
})
},
任何建议都会很棒.谢谢
Any advice would be great. Thanks
推荐答案
Shopify的Ajax API参考可能有助于阐明为什么它对您不起作用.
Shopify's Ajax API reference might help shed some light on why this isn't working for you.
如果您需要一个有效的代码片段来使事情进展,这对我来说是有效的:
If you need a working snippet of code to get things moving, this is working for me:
function removeCartItem(variantId) {
let update = {};
update[variantId] = quantity;
axios({
method: 'post',
url: '/cart/update.js',
data: { updates: update }
})
.then( (response) => {
// The response should confirm the removal of the item from cart.items
// Then you probably want to update your state so cart items gets re-rendered
})
.catch( (error) => {
console.error('Error:', error);
});
}
这篇关于Shopify购物车更新不适用于axios的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!