You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopify中Vue无法渲染Fetch获取的HTML问题求助

解决方案

1. 让Shopify返回JSON格式的集合数据

在你的Shopify集合模板(比如collection.liquid)中添加判断逻辑,当请求头包含application/json时,直接输出集合的JSON数据而非HTML:

{% if request.headers.Accept contains 'application/json' %}
  {{ collection | json }}
{% else %}
  <!-- 保留原有的HTML模板代码 -->
{% endif %}

2. 修正Vue实例代码

原Vue实例的data写法存在错误,需返回对象形式,同时保存实例引用方便后续更新数据:

// 保存Vue实例引用
const app = Vue.createApp({
  data() {
    return {
      collection: collection // 使用你之前定义的collection变量
    }
  }
}).mount('#app');

3. 修改Fetch请求逻辑,更新Vue数据

不再请求HTML内容,改为请求JSON数据,直接更新Vue实例中的collection字段,Vue会自动触发产品网格的重新渲染:

// 筛选器点击处理函数
function handleFilter(variant) {
  // 阻止默认页面跳转行为
  event.preventDefault();
  
  fetch(`/collections?variant=${variant}`, {
    headers: {
      'Accept': 'application/json' // 告知Shopify返回JSON格式数据
    }
  })
  .then(res => res.json())
  .then(newCollection => {
    // 更新Vue数据,触发重新渲染
    app._data.collection = newCollection;
    // 更新浏览器URL,保留历史记录
    history.pushState({}, '', `/collections?variant=${variant}`);
  });
}

4. 处理浏览器前进后退操作

监听popstate事件,当用户点击浏览器前进/后退按钮时,根据当前URL参数重新请求对应数据:

window.addEventListener('popstate', () => {
  const urlParams = new URLSearchParams(window.location.search);
  const variant = urlParams.get('variant');
  
  if (variant) {
    fetch(`/collections?variant=${variant}`, {
      headers: { 'Accept': 'application/json' }
    })
    .then(res => res.json())
    .then(newCollection => {
      app._data.collection = newCollection;
    });
  }
});

5. 绑定筛选器点击事件

给筛选器链接添加点击事件,阻止默认跳转并调用处理函数:

<!-- 原生JS绑定方式 -->
<a href="/collections?variant=black" onclick="handleFilter('black')">黑色</a>
<a href="/collections?variant=white" onclick="handleFilter('white')">白色</a>

或者用Vue指令更规范的写法:

<a href="/collections?variant=black" @click.prevent="handleFilter('black')">黑色</a>

同时在Vue实例的methods中定义处理函数:

const app = Vue.createApp({
  data() {
    return {
      collection: collection
    }
  },
  methods: {
    handleFilter(variant) {
      fetch(`/collections?variant=${variant}`, {
        headers: { 'Accept': 'application/json' }
      })
      .then(res => res.json())
      .then(newCollection => {
        this.collection = newCollection;
        history.pushState({}, '', `/collections?variant=${variant}`);
      });
    }
  }
}).mount('#app');

内容的提问来源于stack exchange,提问作者dbzx10299

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:33:23