Vue V Bind Style

Posted on  by admin
Hi, sorry, I’m fairly new to Vuejs and a junior level programmer and while I think this is something stupid and simple I’m doing wrong, I can’t figure it out after many hours of looking up threads and potential solutions.

I’m trying to change the style reference for a button to a different data source depending on the value of a prop along the lines of this: :style=“this.buttonColorsThemeProp”.

A direct reference :style=“style.btnDarkOne” works correctly and applies the appropriate styling.

In this case this.buttonColorsThemeProp = ‘style.btnDarkOne’ which should reference the correct data property for inline styling.If I used a computed property instead that doesn’t work either:.

I verify that both the prop and the computed property have the correct value (‘style.btnDarkOne’) by printing to the screen which is the reference to the correct data property.

If I paste the data value directly into the “return” value of the computed property (see below), it works, but that’s not what I want to do, I’d rather just reference different data arrays using prop values and applying style conditionally.


Code snippet below. If you only intend to work with modern/evergreen browsers, then using CSS custom properties and variables is the way to go!

You can actually pass CSS custom properties into the :style binding, e.g.

And in your template:. For the CSS, it's just a matter of:.

The advantage of this method is that you can scope CSS custom properties, so these variables will only apply to your specific button component when you define the CSS properties at the element level (instead of in :root).

The only drawback is that you have to iteratively declare all the variables in both hover and unhovered states, which can be a little bit cumbersome.

Kiran Maniya