[英]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.在我的 vue 应用程序中,我希望元标记的内容是网络请求的结果。 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.
为了完成这项工作,我正在学习类星体以使我的应用程序部分 SSR,但我无法弄清楚如何在服务器端渲染完成之前运行一些异步的东西。
Here's a little MRE that isolates the problem.这是隔离问题的一点 MRE。 I try to delay with a promise, then set a value in the
metaData
below....我尝试延迟承诺,然后在下面的元数据中设置一个值
metaData
<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.我已经证明
beforeCreate
正在执行,但我认为正在发生的事情是它在await
上返回一个承诺,而 SSR 只是向前推进。 The initial value for title
ends up in the client's tag, instead of the one I want. title
的初始值最终出现在客户的标签中,而不是我想要的。
Is there a way I can use SSR but do some async work before rendering?有没有一种方法可以使用 SSR 但在渲染之前做一些异步工作?
A way to handle asynchronous data in a server-side rendered Vue app is to use the asyncData
method.在服务器端呈现的 Vue 应用程序中处理异步数据的一种方法是使用
asyncData
方法。 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.您可以通过在 Quasar 应用程序的
quasar.conf.js
文件中设置ssr: true
选项来使用 Quasar 中的asyncData
方法。 You can then use the asyncData
method in your Vue components as shown in the example above.然后,您可以在 Vue 组件中使用
asyncData
方法,如上例所示。
More info: https://nuxtjs.org/docs/features/data-fetching/#async-data更多信息: https ://nuxtjs.org/docs/features/data-fetching/#async-data
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.