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

Vue.js页面数据无法渲染求助:控制台输出正常但页面无显示

Vue3中fetch获取数据能打印但表格不渲染的排查方案

可能的原因及解决步骤:

  • 核对接口返回的数据结构
    查看控制台console.log(data)的输出:

    • 若返回的是嵌套对象(如{ code: 200, data: [用户列表] }),直接赋值this.users = data会导致users不是数组,v-for无法遍历。需改为this.users = data.data(根据实际接口字段调整)。
    • 用console.log(Array.isArray(data))验证data是否为数组,非数组则需转换为数组格式。
  • 检查模板字段与接口字段的一致性
    对比模板中的firstName、lastName、inputTime和接口返回的用户对象字段名是否完全匹配(注意大小写、驼峰/下划线差异,比如接口返回first_name但模板用firstName)。可通过console.log(data[0])打印单个用户对象逐一核对。

  • 触发Vue响应式更新
    若接口返回数据存在特殊情况(如包含不可枚举属性),可替换数组赋值方式以确保响应式:

    // 替换原this.users = data
    this.users = []
    this.users.push(...data)
    
  • 验证v-for的key值
    确认user.id是否存在且唯一,若接口无id字段,可改用其他唯一标识或索引:

    <tr v-for="(user, index) in users" :key="index">
    

你提供的代码参考:

HTML部分:

<div id="app">
    <table>
        <thead>
        <tr>
            <th>Name</th>
            <th>Surname</th>
            <th>Registration time</th>
        </tr>
        </thead>
        <tbody>
<!--                v-if="users.length > 0">-->
        <tr v-for="user in users" :key="user.id">
            <td>{{user.firstName}}</td>
            <td>{{user.lastName}}</td>
            <td>{{user.inputTime}}</td>
        </tr>
        </tbody>
    </table>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> 

Script部分:

const app = Vue.createApp({
    data() {
        return {
            users: []
        }
    },
    async created() {
        try {
            const response = await fetch('http://localhost:8080/api/v1/users/')
            const data = await response.json()
            console.log(data)
            this.users = data
        } catch (error) {
            console.log(error);
        }
    }
})

app.mount('#app')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 02:02:56