首页 > 解决方案 > 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

我不明白为什么它不能以第一种方式工作?为什么我必须单独分配“更深”的数据以使其可用于组件?

提前感谢您的帮助

标签: javascriptvue.jsmeta-tagsheadnuxtjs

解决方案


这很可能是因为head运行之前fetch能够返回数据。Asthis.post被定义为对象,访问是合法的,this.post.webTitle因为它只是未定义的。但是this.post.fields.thumbnail试图访问thumbnail未定义的,这是非法的。

如果您更改data为:

data() {
    return {
      post: {
          fields: {
              thumbnail: ""
          }
      },
    };
  },

我怀疑它会起作用


推荐阅读