Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NuxtJS - Use asyncData method in layout or component

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,
      };
    }
  })
like image 237
pirmax Avatar asked Oct 28 '25 17:10

pirmax


1 Answers

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')
  }
}
like image 153
Aldarund Avatar answered Oct 31 '25 09:10

Aldarund