Shopify 购物车更新不适用于 axios [英] Shopify cart update not working with axios

查看:43
本文介绍了Shopify 购物车更新不适用于 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆