Home > Back-end >  How to add one more style based on condition inside this style binding? Vue.js
How to add one more style based on condition inside this style binding? Vue.js

Time:10-02

How can i add one more extra style but with condition inside the current style binding?

:style="{ 'background-color': bgColor, color: fColor }"

Son inside this binding I need to add one more style borderBottom:2px based on isInCheckout condition. I don't want to use extra computed. Is there any way to implement it in the above inline binding?

CodePudding user response:

you might want to use a single computed property for all styles of this element. for example:

elementStyle(){
      const style = {}
      if(condition1){
        style['background-color'] = backgroundColorValue
      }
      if(condition2){
        style['color'] = colorValue
      }
      if(condition3){
        style['border-bottom'] = borderBottomValue
      }
      ....
      return style
    }

and in the template just do

:style="elementStyle"

CodePudding user response:

Try like in snippet:

new Vue({
  el: '#demo',
  data() {
    return {
      isChecked: false,
      others: false,
      fColor: 'red',
      bgColor: 'violet',
      border: '2px solid blue'
    }
  },
  methods: {
    change() {
      this.isChecked = !this.isChecked
    },
    other() {
      this.others = !this.others
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div :style="[isChecked && {'border-bottom': border}, others && { 'background-color': bgColor, 'color': fColor }] " >
    <h3>text</h3>
    <label for="checked">Border</label>
    <input type="checkbox" id="checked" @click="change" />
    <label for="rest">Rest</label>
    <input type="checkbox" id="rest" @click="other" />
  </div>
</div>

CodePudding user response:

In template

:style="styles"

In script

computed: {
  styles() {
    return isInCheckout
     ? { backgroundColor: bgColor, color: fColor, borderBottom: '2px' }
     : { 'background-color': bgColor, color: fColor }

  }
}
  • Related