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

我想我在方法、插件和异步函数的使用之间迷失了。

任何帮助表示赞赏!

标签: vue.jspluginspromisenuxt.js

解决方案


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 }}。反应系统将完成剩下的工作


推荐阅读