php - 表格Vue组件上没有数据返回
问题描述
我是 Laravel 和 Vue.js 的新手。我需要在 Vue 组件上显示数据。axios.get 响应中的 tableData 变量不为空并返回一个数组。但它没有显示在桌子上。我的代码有问题吗?我正在关注关于 Medium 的教程。
<div class="card-body">
<table class="table">
<thead>
<tr>
<th scope="col">Display Name</th>
<th scope="col">Description</th>
<th scope="col">Created At</th>
</tr>
</thead>
<tbody>
<tr class="" v-if="tableData.length === 0">
<td class="lead text-center" :colspan="columns.length + 1">No data found.</td>
</tr>
<tr v-for="(data, key1) in tableData" :key="data.id" class="m-datatable__row" v-else>
<td>{{ serialNumber(key1) }}</td>
<td v-for="(value, key) in data">{{ value }}</td>
</tr>
</tbody>
</table>
</div>
<script>
export default {
props: {
fetchUrl: { type: String, required: true },
columns: { type: Array, required: true },
},
data() {
return {
tableData: []
}
},
created() {
console.log(this.fetchUrl);
return this.fetchData(this.fetchUrl)
},
methods: {
fetchData(url) {
axios.get(url)
.then(response => {
console.log(response.data.data)
this.tableData = response.data.data
console.log(this.tableData)
})
},
/**
* Get the serial number.
* @param key
* */
serialNumber(key) {
return key + 1;
},
},
filters: {
columnHead(value) {
return value.split('_').join(' ').toUpperCase()
}
},
name: 'Read'
}
</script>
<style scoped>
</style>
控制器
public function getRoleForDataTable(Request $request)
{
$roles = Role::all();
return RoleResource::collection($roles);
}
角色资源.php
public function toArray($request)
{
return [
'name' => $this->name,
'description' => $this->description,
'created_at' => Carbon::parse($this->created_at)->toDayDateTimeString(),
];
}
解决方案
控制器
public function getRoleForDataTable() {
$roles = Role::all();
return response(new RoleResource($roles)); }
角色资源.php
public function toArray($request) {
$itemList = [];
foreach ($this->collection as $item) {
array_push($itemList, [
'id' => $item->id,
'name' => $item->name,
'description' => $item->description,
'created_at'=>Carbon::parse($item->created_at)->toDateTimeString()
]);
}
return $itemList;
}
Vue文件
<table class="table">
<thead>
<tr>
<th scope="col">Serial</th>
<th scope="col">Display Name</th>
<th scope="col">Description</th>
<th scope="col">Created At</th>
</tr>
</thead>
<tbody>
<tr class="" v-if="tableData.length === 0">
<td class="lead text-center" :colspan="columns.length + 1">No data found.</td>
</tr>
<tr v-for="(data, key1) in tableData" :key="data.id" class="m-datatable__row" v-else>
<td>{{ serialNumber(key1) }}</td>
<td>{{ data.name }}</td>
<td>{{ data.description }}</td>
<td>{{ data.created_at }}</td>
</tr>
</tbody>
</table>
推荐阅读
- javascript - 如何使用 Javascript 创建 txt 文件并使用 txt 文件的内容创建一个 html 文件?
- php - 如何从谷歌驱动器获取视频文件的可播放链接
- javascript - 使用没有分区键规范的查询从 Cosmos 中删除文档
- php - 使用 php exec 运行 youtube-dl
- python - 如何指定要在 Python 脚本中更改的 xml 文件中的多个字符串?
- spring - 现有 API 的移动应用程序身份验证
- python - 使用带有列名和值的字典对 Pandas 数据帧进行一次性编码
- javascript - 从反应原生移动项目向本地 api 发送获取请求
- laravel - Laravel 和 Vue:我的布局刀片加载了我的组件看不到的脚本
- python - 将列表中每个元组的元素与列表中的每个元素相乘