如何使用 Nuxt 访问 asyncData 中的数据

Posted

技术标签:

【中文标题】如何使用 Nuxt 访问 asyncData 中的数据【英文标题】:How can I access data in asyncData with Nuxt 【发布时间】:2019-03-21 13:27:26 【问题描述】:

我正在尝试使用 Nuxt 构建服务器端可排序表,我希望能够在我的 Vue data 中指定默认排序列和方向,并在我的 asyncData 函数中访问它.像这样的:

<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.sortColumnthis.sortAscending。我如何在asyncData 运行时访问这些默认值,同时还允许在用户与页面交互时更改它们。 (或者,有什么更好的方法来构建它?)

注意:这个问题被问到here,但接受的答案与这种情况无关。

【问题讨论】:

【参考方案1】:

您可以将其全部返回到 asyncData。例如。像这样:

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 ;
  ,

它会按照你的意愿行事。

【讨论】:

以上是关于如何使用 Nuxt 访问 asyncData 中的数据的主要内容,如果未能解决你的问题,请参考以下文章

“默认 Apollo 查询”VS “AsyncData”(Nuxt.js)

如何测试 nuxt.js asyncData 并获取钩子

Nuxt 和 vue 中的 Data() VS asyncData()

如何在 Nuxt 的 asyncData 中重定向

如何在 Nuxt 的 asyncData 中对 Promise.all 进行数组解构

Nuxt.js asyncData 多请求