我在Vue应用中为博客建立了非常基本的设置,其中/blog
是我的博客文章列表,然后是/blog/:slug
,其中slug是单个文章的博客(例如[ C0]。我使用mysite.com/blog/my-awesome-blog-post
作为meta标记,并且一切正常-除个别博客文章的标记之外,所有内容都适用。我的设置是:
App.vue
vue-meta
Blog.vue
export default {
metaInfo: {
title: 'Building great web experiences',
titleTemplate: 'My Website | %s',
},
meta: [
{ charset: 'utf-8' },
{ name: 'description', content: 'The website for my organization' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' }
]
}
BlogPost.vue(在export default {
metaInfo: {
title: 'Blog Home'
},
之后)
vue-meta docs
问题是,当我转到博客帖子页面时,标题元标记仍为export default {
data() {
metaDescription: '',
},
metaInfo() {
return {
title: this.post.data.title,
meta: [
{ vmid: 'description', name: 'description', content: this.metaDescription}
]
}
},
...
methods: {
getPost() {
const vm = this;
butter.post
.retrieve(this.$route.params.slug)
.then(res => {
vm.post = res.data;
vm.metaDescription = vm.post.data.summary;
})
.catch(res => {
console.log(res);
});
}
},
,而不是My Site | Blog Home
。如果我将静态字符串放入My Site | My Awesome Blog Post
,则可以正常工作。而且,如果我检查Vue devtools中title
函数返回的对象,则它会显示metaInfo()
并带有适当的值。我是在做错什么,还是这是个错误?根据文档,这是“容易的”,但事实并非如此。
正如我在title
中所指出的,我做了一个很小的更改,但却奏效了(实际上,有几个奏效)。首先是创建一个名为comment in the GitHub issue I filed的数据变量,将其填充在metaTitle
中,然后在getPost()
中使用它:
metaInfo()
然后我又尝试了另一种方法,将我的post对象缩小了一个级别:
data() {
return {
post: {},
metaTitle: '',
metaDescription: ''
};
},
metaInfo() {
return {
title: this.metaTitle,
meta: [
{ vmid: 'description', name: 'description', content: this.metaDescription}
]
}
},
methods: {
getPost() {
const vm = this;
butter.post
.retrieve(this.$route.params.slug)
.then(res => {
vm.post = res.data.data;
vm.metaTitle = vm.post.data.title;
vm.metaDescription = vm.post.summary;
})
.catch(res => {
console.log(res);
});
}
},
并在metaInfo()中使用它:
.then(res => {
vm.post = res.data.data;
vm.metaTitle = vm.post.data.title;
vm.metaDescription = vm.post.summary;
})
也许是问题是metaInfo() {
return {
title: this.post.title,
meta: [
{ vmid: 'description', name: 'description', content: this.metaDescription}
]
}
},
数据在对象中的层次不能太高?不确定,但是两种方法都可以。