1

I try to display {{ bgColor }} in my template. But it only displays [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})`
        })
      }
    }
  }

The function looks to work, as I get the result on console.log

rgb(24, 155, 97)

I think I'm lost between methods, the plugin and the use of an async function.

Any help appreciated !

2 Answers2

0

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. If not lifecycle any event like 'click' will be good also

The best thing you probably can do is to change return statement to assign statement

Instead of return 'rgb(${r}, ${g}, ${b})' try this.something = rgb(${r}, ${g}, ${b})' (of course you have to define something in data object). Then just render {{ something }} in your template. Reactivity system will do the rest

BigKamil5
  • 295
  • 3
  • 11
  • Ok Thanks! I tried with : `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) }) } ` That seems to work (console.log is fine) but oddly the value of ´this.bgColor´ is not updated. Any idea ? – user2136034 Mar 04 '20 at 12:45
  • Can you copy paste your whole component somewhere? Codepen or jsFiddle, cause it's kinda hard to tell why it's not working :) – BigKamil5 Mar 05 '20 at 19:17
  • Yes, I tried here : https://codesandbox.io/embed/unruffled-mirzakhani-b8tlk?fontsize=14&hidenavigation=1&theme=dark (thanks for the help !) – user2136034 Mar 09 '20 at 18:25
0

Soo all your Vue logic is good, but promise is never resolved cause of :

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

I've copied it to my local project and I am getting this error

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

You won't be able to draw images directly from another server into a canvas and then use getImageData. It's a security issue and the canvas will be considered "tainted".

Don't know if it will solve your problem but you can download this image. And put to for example inside assets. Then just required it from there. And it will work

BigKamil5
  • 295
  • 3
  • 11