【发布时间】:2021-09-30 14:19:27
【问题描述】:
<template>
<div>
<v-data-table
:headers="headers"
:items="desserts"
:options.sync="options"
:server-items-length="totalDesserts"
:loading="loading"
class="elevation-1"
></v-data-table>
</div>
</template>
<script>
const elasticsearch = require('elasticsearch')
const client = new elasticsearch.Client({
hosts: ['localhost:9200'],
})
export default {
data () {
return {
totalDesserts: 0,
desserts: [],
loading: true,
options: {},
headers: [...],
}
},
watch: {
options: {
handler () {
this.getDataFromApi()
},
deep: true,
},
},
mounted () {
this.getDataFromApi()
},
methods: {
getDataFromApi () {
this.loading = true
this.fakeApiCall().then(data => {
this.desserts = data.items
this.totalDesserts = data.total
this.loading = false
})
},
/**
* In a real application this would be a call to fetch() or axios.get()
*/
fakeApiCall () {
return new Promise((resolve, reject) => {
const { sortBy, sortDesc, page, itemsPerPage } = this.options
let items = this.GetList(1)
console.log(items.then(rs => { return rs }))
items.then(console.log)
const total = items.length
if (sortBy.length === 1 && sortDesc.length === 1) {
items = items.sort((a, b) => {
const sortA = a[sortBy[0]]
const sortB = b[sortBy[0]]
if (sortDesc[0]) {
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 (itemsPerPage > 0) {
items = items.slice((page - 1) * itemsPerPage, page * itemsPerPage)
}
setTimeout(() => {
resolve({
items,
total,
})
}, 1000)
})
},
async GetList (day) {
const result = await client.search({...})
// console.log(result)
if (result.hits.total.value > 0) {
const RsList = new Array(result.hits.hits.length)
for (let x = 0; x < result.hits.hits.length; x++) {...}
// console.log(RsList)
return RsList
} else {
throw new Error('no result')
}
},
},
}
</script>
我编写了这段代码。(它来自 Vuetify 示例代码:https://vuetifyjs.com/en/components/data-tables/#server-side-paginate-and-sort)
GetList 函数返回表的数组。
但是当它运行时 this.GetList(1) 返回 Promise 对象。
就算加上then(this.GetList(1).then(rs => {return rs})也不行....
如何从 GetList 获取返回数组?
【问题讨论】:
-
对于这个问题,
fakeApiCall只是假的吗?如果是,为什么你有问题,你的真实代码不应该只做一个简单的fetch()调用吗? -
啊,这不是假代码。我只是复制 n 粘贴示例代码以了解示例代码的工作原理并添加一些我的代码。
-
嗯,你不应该。
fakeApiCall原本打算被真正的 API 调用完全取代。你绝对需要摆脱new Promise和setTimeout,它们只是作为数据返回承诺的一个例子。你已经有GetList()了。 -
你对,在将 fakeApiCall 更改为异步功能之后。是工作!感谢您的提示!