Vue.js前端无法显示Laravel API返回的数据求助
Laravel 10 + Vue 3 前端无法渲染员工数据问题排查与解决
问题根源分析
数据初始化类型错误
组件data中employees初始值设为Array(构造函数),而非空数组[]。Vue响应式系统依赖正确的初始数据类型,这种写法会导致数据更新时无法触发视图渲染。v-for指令位置错误
将v-for绑定在<tbody>标签上,会为每个员工生成独立的<tbody>,不符合HTML表格规范,同时导致表格结构异常,无法正确渲染数据。正确做法是将v-for绑定在<tr>标签上,单个<tbody>下包含所有员工行。表格结构与语义错误
原代码用<div class="table table-hover">包裹表头和表体,Bootstrap的table类应直接作用于<table>标签;数据行使用<th>而非<td>,违背了表头单元格与数据单元格的语义区分,也会导致样式异常。
修正后的完整代码
<template> <div class="container"> <table class="table table-hover"> <thead> <tr> <th scope="col">#</th> <th scope="col">First Name</th> <th scope="col">Last Name</th> <th scope="col">Birth Date</th> <th scope="col">Gender</th> <th scope="col">Hire Date</th> </tr> </thead> <tbody> <tr v-for="employee in employees" :key="employee.emp_no" class="table-secondary"> <th scope="row">{{ employee.emp_no }}</th> <td>{{ employee.first_name }}</td> <td>{{ employee.last_name }}</td> <td>{{ employee.birth_date }}</td> <td>{{ employee.gender }}</td> <td>{{ employee.hire_date }}</td> </tr> </tbody> </table> </div> </template> <script> import axios from 'axios'; export default { name:'EmployeeList', data() { return { employees: [] // 修正为初始空数组 } }, created() { this.getEmployees(); }, methods:{ async getEmployees() { let url = 'http://127.0.0.1:8000/api/employees'; try { const response = await axios.get(url); this.employees = response.data.employees; console.log(this.employees); } catch (error) { console.log(error); } } }, mounted() { console.log('Employee List Component Mounted'); } } </script>
额外优化说明
- 移除了
async/await与.then()的冗余混用,改用try/catch结构,代码逻辑更清晰。 - 修正了表格标签的语义错误,确保样式与结构符合Bootstrap规范。
内容的提问来源于stack exchange,提问作者Matakoththuwakoni
相关产品推荐
相关产品推荐

