首页 > 解决方案 > 黎明中的 Shopify 购物车 API 捆绑部分呈现

问题描述

我正在尝试使用 Shopify 的基础 Dawn 模板构建一个迷你购物车。

在 assets/cart.js 中,getSectionsToRender 函数提供了来自 data-id 属性的部分 id。然后,这将被绑定到具有捆绑部分渲染的 Cart Api 的提取使用。

  getSectionsToRender() {
    return [
      {
        id: 'main-cart-items',
        section: document.getElementById('main-cart-items').dataset.id || 'main-cart-items',
        selector: '.js-contents',
      },
      {
        id: 'cart-icon-bubble',
        section: 'cart-icon-bubble',
        selector: '.shopify-section'
      },
      {
        id: 'cart-live-region-text',
        section: 'cart-live-region-text',
        selector: '.shopify-section'
      },
      {
        id: 'main-cart-footer',
        section: document.getElementById('main-cart-footer').dataset.id || 'main-cart-footer',
        selector: '#main-cart-footer',
      }
    ];
  }

  updateQuantity(line, quantity, name) {
    this.enableLoading(line);

    const body = JSON.stringify({
      line,
      quantity,
      sections: this.getSectionsToRender().map((section) => section.section),
      sections_url: window.location.pathname
    });

    fetch(`${routes.cart_change_url}`, {...fetchConfig(), ...{ body }})
      .then((response) => {
        return response.text();
      })
      .then((state) => {
        const parsedState = JSON.parse(state);
        console.log(parsedState.sections);
      });
  }

当使用动态部分 id 时,例如template--15179940757682__cart-footer购物车 api 返回完整的 main-cart-footer 元素。但是,动态部分 ID 在其他页面上不可用,在这种情况下,我将main-cart-footer其用作部分 ID。如果没有动态 id,购物车 api 将返回 main-cart-footer,但缺少一些内容。我对 main-cart-items 使用了相同的方法,没有任何问题。

我曾尝试使用sections_url 参数集来/cart指定页面上下文,但这也不起作用。

任何人都知道如何在没有动态部分 id 的情况下获取主购物车页脚?

标签: shopifyshopify-templateshopify-api

解决方案


您是否尝试像“cart-live-region-text”一样创建静态部分?如果您创建这样的部分并在该部分中添加代码(在您的情况下购物车小计更新的购物车页脚),那么您不需要动态部分 ID,您可以编写部分名称(您创建的部分)直接在部分 id 中。您可以查看以下链接 https://shopify.dev/api/section-rendering#find-section-ids


推荐阅读