【问题标题】:Nuxt js : How to display result from a promise in the template?Nuxt js:如何在模板中显示承诺的结果?
【发布时间】:2020-06-13 11:48:43
【问题描述】:

我尝试在我的模板中显示{{ 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.js plugins promise nuxt.js


    【解决方案1】:

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

    【讨论】:

    • 好的,谢谢!我尝试过:created(){ getColorFromURL(process.env.strapiBaseUri+this.project.cover.url).then((res) => { const [r, g, b] = res this.bgColor = rgb(${r}, ${g}, ${b})` console.log('bgColor :' + this.bgColor) }) } ` 这似乎有效(console.log很好)但奇怪的是'this.bgColor'的值没有更新。有什么想法吗?
    • 您可以将整个组件复制粘贴到某处吗? Codepen 或 jsFiddle,因为很难说它为什么不工作:)
    • 是的,我在这里试过:codesandbox.io/embed/…(感谢您的帮助!)
    【解决方案2】:

    所以你所有的 Vue 逻辑都很好,但是承诺永远不会解决原因:

    canvas-image.js?14a5:35 Uncaught (in promise) DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
    

    我已将其复制到我的本地项目中,但出现此错误

    How to fix getImageData() error The canvas has been tainted by cross-origin data?

    您将无法直接从另一台服务器将图像绘制到画布中,然后使用 getImageData。这是一个安全问题,画布将被视为“受污染”。

    不知道它是否能解决您的问题,但您可以下载此图片。并以内部资产为例。然后从那里需要它。它会起作用的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-24
      • 2019-06-01
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      • 2017-08-14
      相关资源
      最近更新 更多