[Vuejs]-Component in Vue.js server-side rendering

0๐Ÿ‘

I have previously incurred into a similar problem and managed to successfully prefetch data by doing the following:

app.$router.onReady(() => {
   const matchedComponents = app.$router.getMatchedComponents()

   if (!matchedComponents.length) { /* ... */}

   Promise.all(matchedComponents.map((Component: any) => {
     if (Component.options.methods.asyncData) {
       return Component.options.methods.asyncData({
         store: app.$store,
         route: app.$router.currentRoute
       });
     }
   })).then(() => { /* your callback here ... */ });
}

According to vue ssr documentation (https://ssr.vuejs.org/en/data.html) the suggested way is to use a custom asyncData method in your component to perform data fetching rather than calling component methods directly:

export default {
   asyncData ({ store, route }) {
      // return the Promise from the action
      return store.dispatch('fetchItem', route.params.id)
   }
},
๐Ÿ‘คDavide

Leave a comment