Vue3 Composition API转写后posts无法渲染问题排查
问题分析与解决方法
你遇到的问题核心是响应式变量的声明或赋值错误,导致异步获取数据后视图没有触发更新,而热更新时Vue重新建立了响应式关联,所以数据能正常显示。下面是具体的错误场景和修正方案:
常见错误1:未用ref声明响应式变量
如果直接用普通变量存储posts,Vue无法追踪其变化:
<script setup> import axios from 'axios' // ❌ 错误:普通变量,无响应式 let posts = [] async function fetchPosts() { const res = await axios.get('https://your-wordpress-site/wp-json/wp/v2/posts') posts = res.data } fetchPosts() </script>
修正:用ref声明响应式数组
<script setup> import axios from 'axios' import { ref } from 'vue' // ✅ 正确:用ref创建响应式变量 const posts = ref([]) async function fetchPosts() { const res = await axios.get('https://your-wordpress-site/wp-json/wp/v2/posts') posts.value = res.data } fetchPosts() </script>
常见错误2:赋值时直接覆盖ref变量
如果错误地直接给ref变量赋值(而不是修改.value),会丢失响应式关联:
<script setup> import axios from 'axios' import { ref } from 'vue' const posts = ref([]) async function fetchPosts() { const res = await axios.get('https://your-wordpress-site/wp-json/wp/v2/posts') // ❌ 错误:直接覆盖ref变量,响应式丢失 posts = res.data } fetchPosts() </script>
修正:修改ref的.value属性
ref包裹的变量必须通过.value访问和修改,Vue才能追踪到变化:
<script setup> import axios from 'axios' import { ref } from 'vue' const posts = ref([]) async function fetchPosts() { try { const res = await axios.get('https://your-wordpress-site/wp-json/wp/v2/posts') // ✅ 正确:修改ref的value属性 posts.value = res.data } catch (err) { console.error('获取文章失败:', err) } } fetchPosts() </script>
模板渲染示例
确保模板中直接使用ref变量(不需要加.value,Vue会自动处理):
<template> <div class="posts-list"> <div v-for="post in posts" :key="post.id" class="post-item"> <h3>{{ post.title.rendered }}</h3> <div v-html="post.excerpt.rendered"></div> </div> </div> </template>
为什么热更新后能正常显示?
当你修改模板并触发热更新时,Vue会重新编译组件,此时会重新检测当前的变量状态并建立响应式关联,所以能正确渲染已获取到的posts数据。但这只是临时的,解决根本问题还是要保证响应式变量的正确声明和赋值。
内容的提问来源于stack exchange,提问作者Larry
相关产品推荐
相关产品推荐

