Inigo
Inigo

Reputation: 8715

How can I bind a linear-gradient background property made up of dynamic variables constituting the color names, angles, etc?

I keep running into this problem. I need to be able to set the background of various elements in my component as dynamic linear gradients. (The context is creating a grid background that scales and adjusts depending on various inputs).

I want to be able to build up my linear-gradient CSS background property dynamically in a function, e.g. here's a simplified version of what I am trying to achieve:

createBackgroundString(){
    return 'linear-gradient(' + this.angle + 'deg, ' + this.color1 + ', ' + this.color2 + ')';
}

...and then stick that into my :style attribute to have Vue apply it dynamically:

v-bind:style="{ background: createBackgroundString() }"

Vue rejects (ignores) this outright, presumably because the resultant string is too complex to fit the property template which expects a simple string like 'red' or '#FF000' etc.

Is there any way/hack/workaround to achieve this in Vue? At the moment I'm having to resort to jQuery for this which is far from ideal.

Upvotes: 5

Views: 8357

Answers (1)

T. Short
T. Short

Reputation: 3614

I can get it to work like this:

<div :style="{ backgroundImage: createBackgroundString }" />

and a computed prop:

data() {
    return {
      angle: '50',
      color1: 'red',
      color2: 'blue'
    }
  },
  computed: {
    createBackgroundString() {
      return `linear-gradient(${this.angle}deg, ${this.color1}, ${this.color2})`;
    }
  }

You don't have to use backticks (`) if you don't want to. I just prefer it.

Note that I have changed createBackgroundString() to createBackgroundString

Upvotes: 6

Related Questions