[Vuejs]-How can I add conditional style in Vue.js?

3👍

You should use the conditional style binding for vue. I’ll show an example:

new Vue({
  el: '#app',
  data: {
    color: "secondary"
  },
  methods: {
    toggleColor(val) {
      this.color = val
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div :style="[color==='primary' ? {color: 'red'} : {color: 'blue'}]">Primary</div>
<div :style="[color==='secondary' ? {color: 'red'} : {color: 'blue'}]">Secondary</div>
<button @click="(e) => toggleColor('primary')">Switch to pirmary</button>
<button @click="(e) => toggleColor('secondary')">Switch to secondary</button>
</div>

Leave a comment