javascript - nuxtjs 头部元标记在 fetch() 上动态修改
问题描述
我在 Nuxtjs 中有这个组件,它呈现使用 API 的 fetch 方法获取的内容。API 将数据作为嵌套对象返回。当我将此数据传递给元标记的 head() 方法时,它仅适用于一层深度,但不适用于嵌套数据。这是为什么?
在这段代码中,我们将接收到的数据分配给组件 data() 中的 const post this.post = data.response.results[0];
。然后在使用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
能够返回数据。Asthis.post
被定义为对象,访问是合法的,this.post.webTitle
因为它只是未定义的。但是this.post.fields.thumbnail
试图访问thumbnail
未定义的,这是非法的。
如果您更改data
为:
data() {
return {
post: {
fields: {
thumbnail: ""
}
},
};
},
我怀疑它会起作用
推荐阅读
- c - C:在cygwin上使用Openssl时声明冲突
- python - 打印错误的python
- python - 如何使用 BeautifulSoup 抓取网站
- sorting - Clojure 重排序函数
- windows - 阻止用户意外执行 .bat 文件
- angular - 如何针对 localhost API(Dev App)运行 Ionic App
- r - 存储循环中的值
- php - 如何在 laravel 中与数据中心 ID 同步
- c# - 多次定义导入的类型`Newtonsoft.Json.Linq.JObject'
- python - 在Python中获取URL中最后两个斜杠位置之间的字符串