NuxtJS - Use asyncData method in layout or component

故事扮演 提交于 2020-06-13 06:49:07

问题


How I can use asyncData in layout or component (forbidden apparently) ?

Because my sidebar component is used in default layout, and I need to use asyncData to display data from backend. And if I use Vuex to fetch data... I don't know how I can fetch this with global on every page.

My layout component annotation:

  @Component({
    components: {
      LeftDrawer
    },
    async asyncData({ app }) {
      const latestPosts = await app.$axios.get(`/posts/latest`);

      return {
        latestPosts: latestPosts.data,
      };
    }
  })

回答1:


fetch and asyncData works only for pages, as it stated in documentation. If you need something to get data on each page, use nuxtServerInit

actions: {
  async nuxtServerInit({ dispatch }) {
    await dispatch('core/load')
  }
}


来源:https://stackoverflow.com/questions/58205391/nuxtjs-use-asyncdata-method-in-layout-or-component

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