Mark
Mark

Reputation: 3738

Style not showing when adding multiple dynamic styles in Vue

I'm not able to add multiple dynamic styles in vue.

Originally it looks like this: (The correct height shows up)

:style="minHeight ? `min-height:${getCSSUnit(minHeight,'inital')}` : ''"

But then I wanted to add another style, hasCss, and from what I've seen I can add another style as show below based on Vue js bind multiple style properties to an element:

:style="[minHeight ? `min-height:${getCSSUnit(minHeight,'inital')}` : '', hasCss]"

Problem is that the hasCss styles shows up but the minHeight doesn't. I thought maybe it has to do with the order of the styles but having:

:style="[hasCss, minHeight ? `min-height:${getCSSUnit(minHeight,'inital')}` : '']"

results in the same thing. In fact, as soon as I put the [] the minHeight style stops working. What am I doing wrong?

The hasCss computed property looks like:

hasCss() {
      return {
        '--color': this.textColour
      }
    }

Upvotes: 1

Views: 566

Answers (1)

Mark
Mark

Reputation: 3738

Figured it out, problem is when using [] to include multiple dynamic styles, the styles are expected to be in object format. eg:

data() {
  return {
      baseStyles: {
      fontWeight:'800',
      color: 'red'
    },
      overrideStyles: {
      color:'blue'
    } 
  }
}

<p :style="[baseStyles, overrideStyles]">
  baseStyles and overrideStyles
</p>

In my case hasCss returns an object but the existing style min-height was expressed in CSS format min-height:${getCSSUnit(minHeight,'inital')}, not in object format. I therefore moved the min-height style to hasCss,

hasCss() {
      return {
        'min-height': this.getCSSUnit(this.minHeight,'inital'),
        '--color': this.textColour
      }
    }

And :style="hasCss"

Upvotes: 1

Related Questions