首页 > 解决方案 > Nuxt head() 不等待 head 的 asyncData 响应

问题描述

我有这样的 nuxt 代码

<template>
  <section>
    <div>Hello Nuxt</div>
  </section>
</template>

<script>
const fetchTheme = () => {
  return new Promise(function(resolve, reject) {
    setTimeout(() => {
      resolve({
        title: "Fetched Title"
      });
    }, 100);
  });
};

export default {
  async asyncData() {
    const theme = await fetchTheme();
    return theme;
  },

  head() {
    if (this.theme) {
      return {
        title: this.theme.title
      };
    } else {
      return {
        title: "Default title"
      };
    }
  }
};
</script>

<style scoped>
</style>

虽然我确实查看源代码,但它给出了“默认标题”,但我需要从 API 获取的标题这是代码代码沙箱

标签: vue.jsurl-routingnuxt.js

解决方案


从 asyncData 上的文档

Nuxt.js 会自动将返回的对象与组件数据合并。

这意味着你在做什么:

  async asyncData() {
    const theme = await fetchTheme();
    return theme;
  }

类似于此:

  async asyncData() {
    const theme = await fetchTheme();
    return {
      title: theme.title
    };
  }

这意味着可以通过执行this.title而不是访问标题this.theme.title

要解决此问题,只需修改 asyncData 的返回格式,以返回具有主题属性的对象:

  async asyncData() {
    const theme = await fetchTheme();
    return {
       theme
    };
  }

这会将属性正确添加themedata组件的属性中。


推荐阅读