Search code examples
vue.jsbuttonhighlight

VueJS - How to highlight selected button when clicked


I have 3 buttons that shows a chart when clicked on it respectively. Here below is the buttons for example:

enter image description here

Whenever the button is clicked respective chart is shown, but I want to keep the button highlighted with red color while the chart is shown.

<vs-button color="warning" @click="chartClick($event, 'chart1')" vs-value="chart1" v-model="show"> chart1</vs-button>

<vs-button color="warning" @click="chartClick($event, 'chart2')" vs-value="chart2" v-model="show"> chart2 </vs-button>

<vs-button color="warning" @click="chartClick($event, 'chart3')" vs-value="chart3" v-model="show"> chart3 </vs-button>

<script>
data () {
  return {
    show = false
  }
},
mounted (){
  chartClick (chart1)
},
methods: {
  chartClick (event, id){
    
    ...
    this.show = true
  }
}
</script>

Please help me in this, i want to know how to highlight the button, when the chart is shown.

And also i want to know how to display chart1 with button1 (chart1) highlighted when the page is loaded or runned at first.


Solution

  • You can do that by adding one more variable in data section, for example:

    data () {
      return {
        show : false,
        activeChart : '',
      }
    }
    

    You should not use variableName = defaultValue, it should be variableName : defaultValue.

    and then add to your buttons:

    :class="{activeChartClass: activeChart === 'chart1'}"
    

    Note: are you sure v-model is supported on vs-button tag?

    also you will have to add this to your chartClick method:

    this.activeChart = id;
    

    and finally add a CSS class to edit your active button:

    .activeChartClass {
        background-color: red!important;
    }
    

    You can read more about class and style binding here: https://v2.vuejs.org/v2/guide/class-and-style.html#Object-Syntax