我在Nuxtjs中有这个组件,它呈现使用API获取方法获取的内容。API 将数据作为嵌套对象返回。当我将此数据传递给元标记的 head(( 方法时,它仅适用于一级深度,但不适用于嵌套数据。为什么?
在此代码中,我们将收到的数据分配给组件 data((this.post = data.response.results[0];
中的 const post。然后,当使用this.post.webTitle
它很好,但是当使用this.post.fields.thumbnail
时,会出现一个错误,指出缩略图未定义。
export default {
async fetch() {
const { data } = await this.$axios.get(
`api_url`
);
this.post = data.response.results[0];
this.loading = false;
},
data() {
return {
post: {},
};
},
head() {
return {
title: this.post.webTitle ? `${this.post.webTitle.slice(0, 10)}...` : "",
meta: [
{
hid: "description",
name: "description",
content: this.post.webTitle,
},
{ hid: "og-title", property: "og:title", content: this.post.webTitle },
{
hid: "og-image",
property: "og:image",
content: this.post.fields.thumbnail,
},
{ hid: "og-image-width", property: "og:image:width", content: 500 },
{ hid: "og-image-height", property: "og:image:height", content: 300 },
{
hid: "og-image-type",
property: "og:image:type",
content: "image/jpeg",
},
],
};
},
};
单独分配时
this.post = data.response.results[0];
this.thumbnail = data.response.results[0].fields.thumbnail;
data() {
return {
post: {},
thumbnail: "",
};
},
那么它工作正常,我可以使用:
this.thumbnail
我不明白为什么它不能以第一种方式工作?为什么我必须单独分配"更深"的数据才能使其可用于组件?
提前感谢您的帮助
这很可能是因为head
在fetch
能够返回数据之前运行。由于this.post
被定义为对象,因此访问this.post.webTitle
是合法的,因为它只是未定义。但是this.post.fields.thumbnail
试图访问未定义的thumbnail
,这是非法的。
如果将data
更改为:
data() {
return {
post: {
fields: {
thumbnail: ""
}
},
};
},
我怀疑它会起作用