【问题标题】:How can I access data in asyncData with Nuxt如何使用 Nuxt 访问 asyncData 中的数据
【发布时间】: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,但接受的答案与这种情况无关。

【问题讨论】:

    标签: vue.js nuxt.js


    【解决方案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 };
      },
    

    它会按照你的意愿行事。

    【讨论】:

      猜你喜欢
      • 2020-09-12
      • 1970-01-01
      • 2021-12-28
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 2022-11-11
      • 1970-01-01
      • 2020-03-09
      相关资源
      最近更新 更多