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

Vue3结合Liquid时如何传{% raw %}捕获的handle获取Shopify对象

问题核心原因

Liquid是Shopify服务端执行的预渲染模板语言,所有Liquid逻辑会在页面发送到用户浏览器、Vue框架初始化之前全部执行完成;而Vue的v-for循环、featuredHandlesArray变量都是客户端浏览器环境下运行的逻辑,二者执行时机完全隔离,不存在运行时互传值的可能。
你原写法里的{% raw %}{{ handle }}{% endraw %}只是把字面量字符串{{ handle }}存入了article_liquid变量,Liquid执行阶段根本拿不到Vue运行时的真实handle值。你之前能在页面上看到正确的handle输出,是Vue在客户端完成渲染后,把DOM里的{{ handle }}插值文本替换成了真实值,并非Liquid成功获取到了Vue的变量,因此用articles[article_liquid]查询时,实际传入的是字符串{{ handle }},自然匹配不到任何文章对象。

可行解决方案

根据你的业务场景选对应方案即可:

方案1:服务端预加载目标文章数据(推荐,性能最优)

如果featuredHandlesArray的内容是可在服务端预知的(比如来自主题配置项、固定博客下的精选文章),直接在Liquid层提前把需要的文章对象序列化成全局JSON数据,Vue初始化时直接读取使用即可,不需要在客户端循环中反查Shopify对象。
示例代码:

{% comment %} 提前将需要的文章字段序列化,注入全局供Vue调用 {% endcomment %}
<script>
window.preloadedArticles = [
  {% for article in blogs.news.articles | where: "handle", in: target_handle_list %}
    {{ article | json }}{% unless forloop.last %},{% endunless %}
  {% endfor %}
]
</script>

Vue逻辑中直接遍历window.preloadedArticles即可拿到完整的文章对象属性,无需额外查询。

方案2:客户端动态请求文章数据

如果featuredHandlesArray是用户交互后动态生成、服务端无法提前预知完整列表的,直接在Vue逻辑中调用Shopify Storefront接口,传入handle查询对应文章对象即可,不要尝试让Liquid读取Vue运行时变量。
核心请求逻辑示例:

// Vue方法内,传入handle查询文章
const fetchArticleByHandle = async (handle) => {
  const response = await fetch(`/api/2024-04/graphql.json`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Shopify-Storefront-Access-Token': window.Shopify?.storefrontAccessToken
    },
    body: JSON.stringify({
      query: `query ArticleQuery($handle: String!) {
        blogByHandle(handle: "news") {
          articleByHandle(handle: $handle) {
            id
            title
            url
            excerpt
            content
            image {
              url
              altText
            }
          }
        }
      }`,
      variables: { handle }
    })
  })
  const result = await response.json()
  return result.data?.blogByHandle?.articleByHandle
}

方案3:预生成全量文章映射表(适合文章总量少的场景)

如果你的博客文章总量不多,可以直接在Liquid层生成handle到文章对象的全局映射表,Vue运行时拿到handle后直接查表即可,不需要额外发请求。
示例代码:

<script>
window.articleHandleMap = {
  {% for article in blogs.news.articles %}
    "{{ article.handle }}": {{ article | json }}{% unless forloop.last %},{% endunless %}
  {% endfor %}
}
</script>

Vue逻辑中拿到handle后,直接读取window.articleHandleMap[handle]就能拿到对应的完整文章对象。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 16:12:16