Nuxt3中Pinia调用Server路由获取Firestore评论返回undefined
问题原因
comments打印为undefined是两处逻辑错误导致,不是组件fetch写法的单一问题:
- Pinia中定义的
fetchCommentsaction没有返回值,组件中await调用该函数时,默认拿到undefined - Nuxt 3的
useFetch返回的data是响应式Ref对象,直接将Ref赋值给store的commentsstate,会导致state存储的是RefImpl实例而非实际的评论数组,后续读取值会出现异常 - 服务端API路由在查询不到匹配评论时直接写空
return,没有返回任何内容,会给前端返回204空响应,容易触发取值报错
修复步骤
1. 调整Pinia Store代码
修改/stores/comments.ts,读取Ref的实际值赋值给state,同时给action增加返回值:
import {defineStore} from 'pinia' export const useComment = defineStore('comment', { state: () => { return { comments: [] } }, actions: { async fetchComments(routeParamsId: string) { console.log(1, routeParamsId) const {data} = await useFetch(`/api/comments/${routeParamsId}`) console.log(2, data.value) // 读取Ref的实际值,兼容接口返回空的情况 this.comments = data.value || [] // 返回最终结果,组件侧await才能拿到正确值 return this.comments } } })
2. 调整服务端路由空值逻辑
修改server/api/comments/[postId].ts,无匹配评论时返回空数组,不要空返回:
import { firestore } from '@/server/utils/firebase' export default defineEventHandler(async (event) => { const commentsRef = firestore.collection('comments') const snapshot = await commentsRef.where('postId', '==', event.context.params.postId).get() const comments = [] if (snapshot.empty) { console.log('No matching documents.') // 空结果返回空数组,避免前端拿到空响应 return comments } snapshot.forEach(doc => { comments.push(doc.data()) }) return comments })
3. 组件侧代码说明
现有comments.vue的写法不需要大改,修复上述两处问题后,代码中定义的comments变量就能正常拿到评论数组,store内的commentStore.comments也会是正确的数组格式:
<script setup> import { useComment } from '@/stores/comment' const route = useRoute() const commentStore = useComment() const comments = await commentStore.fetchComments(route.params.id) console.log(3, comments) // 修复后会正常打印评论数组内容 </script>
补充注意:如果评论是在客户端路由切换时触发加载,更推荐在Pinia action中使用
$fetch替代useFetch,避免useFetch在非组件/路由顶层上下文调用的潜在兼容问题。
内容的提问来源于stack exchange,提问作者redshift
相关产品推荐
相关产品推荐

