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

Nuxt Apollo与useAsyncQuery:数据使用、变量赋值及路由问题排查

Nuxt3 + Nuxt Apollo 常见问题解决

核心问题根源

你遇到的页面导航时undefined、变量赋值失败、SEO Meta取不到数据,本质都是响应式数据的时机问题:useAsyncQuery返回的page是Vue响应式ref对象,客户端导航时数据是异步加载的,同步取值/直接赋值会因数据未就绪拿到undefined。


1. 修复页面导航时的undefined错误

直接在模板中添加可选链保护,避免数据未加载时抛出错误:

<template>
  <p>This is my page content: {{ page?.entry?.children }}</p>
</template>

2. 正确赋值myPage简化模板

不要同步直接赋值,用computed响应式依赖page,确保数据更新时自动同步:

<template>
  <p>This is my page content: {{ myPage }}</p>
</template>

<script setup>
import { myQuery as query } from '@/graphql/queries'
import { computed } from 'vue'

const variables = { limit: 5 }
const { data: page } = await useAsyncQuery(query, variables)

// 用computed包装,自动处理数据加载状态
const myPage = computed(() => page?.entry?.children || '内容加载中...')
</script>

3. 修复useSeoMeta的undefined问题

useSeoMeta的回调需要正确访问响应式ref的value属性,或用computed包装确保数据就绪:

方案一:直接在回调中处理

<script setup>
// ... 其他代码
useSeoMeta({
  title: () => page?.value?.entry?.metaTitle || '默认标题'
})
</script>

方案二:用computed包装更稳妥

<script setup>
import { myQuery as query } from '@/graphql/queries'
import { computed } from 'vue'

const variables = { limit: 5 }
const { data: page } = await useAsyncQuery(query, variables)

const pageMetaTitle = computed(() => page?.value?.entry?.metaTitle || '默认标题')

useSeoMeta({
  title: pageMetaTitle
})
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 13:35:16