Javascript 如何在Nuxt中的page meta head属性之前等待post数据?

Javascript 如何在Nuxt中的page meta head属性之前等待post数据?,javascript,vue.js,nuxt.js,vue-meta,Javascript,Vue.js,Nuxt.js,Vue Meta,我正在使用Nuxt SSR动态注入设置页面级元数据的。数据正在从Firebase获取。我得到未定义的属性,因为它不等待post数据加载完成。如何在head属性之前等待post数据 client.js?16a3:97 TypeError: Cannot read property 'post' of undefined //页面\:post.vue 从“vuex”导入{mapState,mapActions} 导出默认值{ fetch(){ this.fetchPost() }, 计算:{ …

我正在使用Nuxt SSR动态注入设置页面级元数据的。数据正在从Firebase获取。我得到未定义的属性,因为它不等待post数据加载完成。如何在head属性之前等待post数据

client.js?16a3:97 TypeError: Cannot read property 'post' of undefined
//页面\:post.vue
从“vuex”导入{mapState,mapActions}
导出默认值{
fetch(){
this.fetchPost()
},
计算:{
…mapState('posts',['post']),
},
方法:{
…映射操作('posts',['fetchPost']),
},
负责人:{
标题:this.post.title,
链接:[{rel:'canonical',href:this.post.canonical}],
元:[
{hid:'name',itemprop:'name',content:this.post.title},
{
hid:“描述”,
itemprop:'说明',
内容:this.post.content,
},
],
},
}
//store\posts.js
导出常量状态=()=>({
post:null,
})
导出常量突变={
设置柱(状态、有效载荷){
state.post=有效载荷
},
}
导出常量操作={
异步fetchPost({commit},key){
const doc=wait postsCollection.doc(key.get)()
如果(doc.exists)提交('setPost',doc.dat())
},

}
可以将构造头部(对象)的方式更改为函数

head() {
    retun {
        title: this.post.title,
        link: [
            { rel: 'canonical', href: this.post.canonical }
        ],
        meta: [
            { hid: 'name', itemprop: 'name', content: this.post.title },
            {
                hid: 'description',
                itemprop: 'description',
                content: this.post.content,
            },
        ],
    }
}

我在GitHub上读到了类似的帖子。由于您使用的是store,我假设您也在使用asyncData函数获取它们。

为什么要使用store,您是否到处都需要相同的head meta信息?我使用store来管理馈送到多个组件的状态。主页和杂项页面通过nuxt.config.js进行全局处理。我正在使用页面级别的head meta来处理帖子页面,这些页面是用户为SEO目的生成的内容。使用head方法会有所帮助,但它仍然不会等待
这个。在运行代码之前,post
填充。是否可以监视
此。post
变为
!空
然后运行此代码?您可以向您的观察者添加帖子。当值更改时,应该更新。你可以阅读更多关于观察者的内容。我尝试过这样的观察者
watch:{post(){this.head()},},
,但它不起作用。因为head方法在第一页加载时运行,并且观察者不会触发
head()
来重新加载元。在执行head方法之前,我是否对观察者做了一些错误的事情,或者以某种方式观察了
this.post
?您应该对观察post变量的方式感到满意。但是您必须在该方法中设置一个变量,而不是运行
this.head()
。您这样做是为了使head是异步的,您应该在head中需要等待的变量前面放置一个
await
。例如,在返回头部时,您必须等待标题:
title:wait this.post.title
。对不起,我的错。你的第一个答案非常有效。只需将
head:{}
更改为
head(){}
即可正常工作,无需使用观察程序。