nuxtjs head meta tag动态修改fetch()

问题描述 投票:0回答:1

我在Nuxtjs中拥有此组件,该组件呈现使用API​​的提取方法提取的内容。 API将数据作为嵌套对象返回。当我将此数据传递给meta标签的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

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

谢谢您的帮助

javascript vue.js meta-tags head nuxtjs
1个回答
1
投票

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

如果将data更改为:

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

我怀疑它会起作用

© www.soinside.com 2019 - 2024. All rights reserved.