How can I access data in asyncData with Nuxt

柔情痞子 提交于 2021-01-27 13:54:19

问题


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>

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.


回答1:


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.



来源:https://stackoverflow.com/questions/52845184/how-can-i-access-data-in-asyncdata-with-nuxt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!