chon
chon

Reputation: 13

Is there a way to bind more than one style value in vue.js

I want so make a div who's box shadow values can be changed using a slider but I can't seem to use more than one value stored in a data variable. Is there any way that I can do this?

<div :style="{ borderRadius: x_axis y_axis blur + 'px' spread color }" ></div>

Vue data:

data: {
  x_axis: 0,
  y_axis: 0,
  blur: 10,
  spread: 0,
  color: rgba(0,0,0,0.1)
}

Upvotes: 1

Views: 206

Answers (1)

Terry
Terry

Reputation: 66113

Yes, you can just use string interpolation using template literals. I strongly recommend you abstracting all that logic into a computed property, which makes your template way more readable:

<div :style="styleObject"></div>

Then, as a computed property, it will look like the following. I recommend suffixing px to all length properties, so that you don't run into errors if the values are non-zero (assuming you intend them to be pixel values):

computed: {
    styleObject() {
        return {
            boxShadow: `${this.x_axis}px ${this.y_axis}px ${this.blur}px ${this.spread}px ${this.color}`
        };
    }
}

You can even make it multiline (template literals allow line breaks) to make things a wee bit more readable:

computed: {
    styleObject() {
        return {
            boxShadow: `${this.x_axis}px
                           ${this.y_axis}px
                           ${this.blur}px
                           ${this.spread}px
                           ${this.color}`
        };
    }
}

Upvotes: 3

Related Questions