vue.js - Nuxt js:如何在模板中显示承诺的结果?
问题描述
我尝试{{ bgColor }}
在我的模板中显示。但它只显示[object Promise]
const { getColorFromURL } = require('color-thief-node')
export default {
data() {
return {
api_url: process.env.strapiBaseUri,
bgColor: this.updateBgColor(this.project),
}
},
props: {
project: Object,
},
methods: {
updateBgColor: async function(project){
return await getColorFromURL(process.env.strapiBaseUri+this.project.cover.url).then((res) => {
const [r, g, b] = res
console.log( `rgb(${r}, ${g}, ${b})` )
return `rgb(${r}, ${g}, ${b})`
})
}
}
}
该功能看起来可以工作,因为我在 console.log 上得到了结果
rgb(24, 155, 97)
我想我在方法、插件和异步函数的使用之间迷失了。
任何帮助表示赞赏!
解决方案
https://forum.vuejs.org/t/render-async-method-result-in-template/36505/3
Render is sync. You should call this method from created or some other suitable lifecycle hook and save the result in component’s data, then render that data.
如果不是生命周期,任何像“点击”这样的事件也会很好
您可能做的最好的事情是将 return 语句更改为 assign 语句
而不是return 'rgb(${r}, ${g}, ${b})'
尝试this.something = rgb(${r}, ${g}, ${b})'
(当然你必须something
在数据对象中定义)。然后只需在您的模板中渲染 {{ something }}。反应系统将完成剩下的工作
推荐阅读
- google-api - Google My Business API:获取评论的问题
- matplotlib - 使用动画为多个绘图中的多条线设置动画
- scala - 在 Java/Scala 程序中从 DataStream 创建 SQL 表并从 SQL 客户端 CLI 查询它 - Apache Flink
- node.js - 错误:解析器中定义了“用户”,但架构中没有
- python - 为什么我的 Flask 错误处理程序没有被调用?
- python - 在 Python Dash 中显示 matplotlib 和 seaborn 图形不起作用。我们怎样才能让它发挥作用?
- stripe-payments - Stripe API 订阅流程?
- sql - 在可选字符串之前匹配内容
- android - 避免静态视图引用,但启用不同的活动来修改视图
- c# - 如何使用 Dapper 从 PostgreSQL 函数中读取多个结果集?