简体   繁体   中英

How to do async in quasar before rendering

In my vue app, I want the contents of a meta tag to be the result of a network request. To get this done, I'm learning quasar to make my app partially SSR, but I can't figure out how to run something async before a server-side render completes.

Here's a little MRE that isolates the problem. I try to delay with a promise, then set a value in the metaData below....

<script>
import { defineComponent } from 'vue'
import { useMeta } from 'quasar'

const metaData = {
  // sets document title
  title: 'title initial value',

  // optional; sets final title as "Index Page - My Website", useful for multiple level meta
  titleTemplate: title => `The title is: ${title}`,

  // meta tags
  meta: {
    // note: for Open Graph type metadata you will need to use SSR, to ensure page is rendered by the server
    ogTitle: {
      property: 'og:title',
      // optional; similar to titleTemplate, but allows templating with other meta properties
      template (ogTitle) {
        return `${ogTitle} - My OG Website`
      }
    }
  }
}

const delay = time => new Promise(resolve => setTimeout(resolve, time))

export default defineComponent({
  async beforeCreate () {
    await delay(3000)
    // I want this to be in the rendered page
    metaData.title = 'title, initialized after a delay'
  },
  setup () {
    useMeta(metaData)
  },
  name: 'IndexPage'
})
</script>

I've proven that beforeCreate is being executed, but I think what's happening is that it returns a promise on the await , and the SSR just plows ahead. The initial value for title ends up in the client's tag, instead of the one I want.

Is there a way I can use SSR but do some async work before rendering?

A way to handle asynchronous data in a server-side rendered Vue app is to use the asyncData method. This method is called before the server-side render occurs. It allows you to perform asynchronous operations.

For example:

export default {
    async asyncData({ params, $http }) {
      const post = await $http.$get(`https://api.nuxtjs.dev/posts/${params.id}`)
      return { post }
    }
  }

You can use the asyncData method in Quasar by setting the ssr: true option in your Quasar app's quasar.conf.js file. You can then use the asyncData method in your Vue components as shown in the example above.

More info: https://nuxtjs.org/docs/features/data-fetching/#async-data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM