如果我return Record::all();
将Axios用于Vuetify数据表,则会显示数据。但如果我使用return RecordResource::collection(Record::all());
,数据甚至不会存储在局部变量中。
我检查了网络选项卡中的数据并且数据存在,但是在Vue选项卡中,数据表中没有数据。没有错误。
这是我的控制人员:
<?php
namespace App\Http\Controllers;
use App\Record;
use Illuminate\Http\Request;
use App\Http\Resources\RecordResource;
use App\Http\Resources\RecordCollection;
class RecordController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return RecordResource::collection(Record::all());
}
}
这是我的Vuejs剧本:
<script>
export default {
data () {
return {
search: '',
totalItems: 0,
items: [],
loading: true,
pagination: {},
headers: [
{
text: 'Teacher Name',
align: 'left',
value: 'user'
},
{ text: 'Type', align: 'center', value: 'type' },
{ text: 'Time', align: 'center', value: 'time' }
]
}
},
watch: {
pagination: {
handler () {
this.getDataFromApi()
.then(data => {
this.items = data.items
this.totalItems = data.total
console.log(this.items)
})
},
deep: true
}
},
mounted () {
this.getDataFromApi()
.then(data => {
this.items = data.items
this.totalItems = data.total
})
},
methods: {
getDataFromApi () {
this.loading = true
return new Promise((resolve, reject) => {
const { sortBy, descending, page, rowsPerPage } = this.pagination
let items = []
this.$http.get('http://localhost:8000/api/records')
.then(response => {
items = response.data
})
.catch(error => {
console.log(error);
});
const total = items.length
if (this.pagination.sortBy) {
items = items.sort((a, b) => {
const sortA = a[sortBy]
const sortB = b[sortBy]
if (descending) {
if (sortA < sortB) return 1
if (sortA > sortB) return -1
return 0
} else {
if (sortA < sortB) return -1
if (sortA > sortB) return 1
return 0
}
})
}
if (rowsPerPage > 0) {
items = items.slice((page - 1) * rowsPerPage, page * rowsPerPage)
}
setTimeout(() => {
this.loading = false
resolve({
items,
total
})
}, 1000)
})
}
}
}
</script>
我的记录资源看起来像这样
public function toArray($request)
{
return [
'user' => User::find($this->user_id)->fname . " " . User::find($this->user_id)->mname . " " . User::find($this->user_id)->lname,
'type' => $this->created_at->hour < 12 ? 'Morning ' . $this->type : 'Afternoon ' . $this->type,
'time' => $this->created_at->toDayDateTimeString()
];
}
}
来自API资源的示例数据
// 20180227062317
// http://localhost:8000/api/records
[
{
"user": "Chadd Q. Rau",
"type": "Afternoon In",
"time": "Sun, Jan 28, 2018 8:22 PM"
},
{
"user": "Rosalind J. Sanford",
"type": "Morning In",
"time": "Tue, Jan 23, 2018 12:15 AM"
},
{
"user": "Rosalind J. Sanford",
"type": "Morning In",
"time": "Mon, Feb 12, 2018 12:45 AM"
}
]
答案 0 :(得分:1)
为什么要创建项变量,而是在vie data()
中定义数据字段data(){
return {
item : {}
}
}
现在在你的axios
axios.get('http://localhost:8000/api/records')
.then(response => {
this.items = response.data
})
.catch(error => {
console.log(error);
});
如果您正在使用resource :: collection,那么您可能需要在.then部分中说出response.data.data