vue.js - 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 获取的标题这是代码代码沙箱
解决方案
从 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
};
}
这会将属性正确添加theme
到data
组件的属性中。
推荐阅读
- android - 如何使用改造 2.0 解析 XML 响应?
- apache-spark - 如何在pySpark中有条件地替换值并将替换后的值用于下一个条件
- vue.js - 映射的 getter 未定义
- python - Python ODBC Create Table IF Not Exists
- html - cakephp 2.x how to include files from external template css
- c# - “无法创建目录,因为目录不存在”
- javascript - Mathjax automatic linebreak when opened in a modal
- excel - 为什么在调整用作列表框的行源的表/列表对象的大小后 Excel 会冻结?
- java - 升级到 android studio 3.2.0 时自定义样式属性不起作用
- xslt - eXist-db / XSLT / Saxon collection() 像糖蜜一样慢(或内存限制出错)