[Vuejs]-Vue: applying css class if specific condition is met

0👍

You could use a class binding that activates the dotActive class for a specific span only when activeSlider matches the span‘s slider index:

<span v-for="slider in sliderCount"
      :class="{ dotActive: slider === activeSlider }">
new Vue({
  el: '#app',
  data: () => ({
    activeSlider: 1,
    sliderCount: 3,
  }),
  methods: {
    slide(diff) {
      let slider = (this.activeSlider + diff) % (this.sliderCount + 1);

      // wrap around
      if (slider === 0) {
        slider = (diff > 0)
          ? 1
          : this.sliderCount;
      }

      this.activeSlider = slider;
    },
  }
})
#app {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}
.button_container {
  margin: 20px; 
}
.slider_dots_container {
  width: 5%;
  display: flex;
  justify-content: space-around;
}
.slider_dots_dot {
  border: solid 2px lightgray;
  border-radius: 50%;
  height: 1px;
}
.dotActive {
  border-color: black;
}
<script src="https://unpkg.com/vue@2.5.17"></script>

<div id="app">
  <div class="button_container">
    <button @click="slide(-1)">Prev</button>
    <button @click="slide(1)">Next</button>
    {{activeSlider}}
  </div>
  <div class="slider_dots_container">
    <span v-for="slider in sliderCount"
          :key="slider"
          class="slider_dots_dot"
          :class="{ dotActive: slider === activeSlider }">
    </span>
  </div>
</div>

1👍

You can use this:

:class="{'activeDotClass':variableThatReturnsTrueOrFalse}"

Basically what you are doing is using javascript inside the {}. Remember to bind the :class with ":"

Here is more in class & style binding:
https://v2.vuejs.org/v2/guide/class-and-style.html

0👍

You can use class binding as follows:

<div v-bind:class="{ active: isActive }"></div>

Where ‘isActive’ is a Boolean variable that controls wether or not class ‘active’ is active or not.

This example was taken directly out of the Vue.js official documentation found online @ www.vuejs.org

Leave a comment