如何使用 Nuxt 访问 asyncData 中的数据 [英] How can I access data in asyncData with Nuxt
问题描述
我正在尝试使用 Nuxt 构建一个服务器端可排序表,我希望能够在我的 Vue data
中指定默认的排序列和方向,并在我的 asyncData
函数.像这样:
I'm attempting to build a server-side sortable table with Nuxt, and I'd like to be able to specify the default sort column and direction in my Vue data
, and access that in my asyncData
function. Something like this:
<script>
export default {
async asyncData ({ $axios, params }) {
const things = await $axios.$get(`/api/things`, {
params: {
sort_column: this.sortColumn,
sort_ascending: this.sortAscending,
}
});
return { things };
},
data () {
return {
sortColumn: 'created_at',
sortAscending: true
}
},
// ...
}
</script>
但似乎 data
尚不可用,因为 this.sortColumn
和 this.sortAscending
未定义.我如何在 asyncData
运行时访问这些默认值,同时还允许在用户与页面交互时更改它们.(或者,有什么更好的方法来构建它?)
But it appears that data
is not yet available, as this.sortColumn
and this.sortAscending
are not defined. How can I access these defaults when asyncData
runs while also allowing them to be changed when the user interacts with the page. (Alternatively, what's a better way to structure this?)
注意:在此处询问了这个问题,但接受的答案是与这种情况无关.
Note: This question was asked here, but the accepted answer is not relevant to this situation.
推荐答案
您可以将其全部返回到 asyncData 中.例如.像这样:
You can just return it all into asyncData. E.g. something like this:
async asyncData ({ $axios, params }) {
const sortColumn = 'created_at'
const sortAscending = true
const things = await $axios.$get(`/api/things`, {
params: {
sort_column: sortColumn,
sort_ascending: this.sortAscending,
}
});
return { things, sortColumn, sortAscending };
},
它会像你想要的那样表现.
And it will behave like you want.
这篇关于如何使用 Nuxt 访问 asyncData 中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!