Using Vue to dynamically add a CSS class based on a specific condition

I am in the process of creating a custom image slider with vuex and I would like to assign a specific class to the navigation dots used for sliding through the images. When a dot is active, it should have a class called dotActive. I intend to use the activeSlider variable for this purpose.

Below is the code snippet for the slider component:

<template>
<section class="slider_maincontainer">
    <transition-group name="slider-fade">
        <div class="slider_item" v-show="activeSlider===1" style="background-color:red;">
            <!--slider content-->
        </div>
        <div class="slider_item" v-show="activeSlider===2" style="background-color:blue;">
            <!--slider varied content-->
        </div>
        <div class="slider_item" v-show="activeSlider===3" style="background-color:green;">
            <!--another slider-->
        </div>
    </transition-group>
    <button class="slider_buttom_prev" @click="prevSlider()">
        <i class="slider_buttom_icon fas fa-angle-left"></i>
    </button>
    <button class="slider_buttom_next" @click="nextSlider()">
        <i class="slider_buttom_icon fas fa-angle-right"></i>
    </button>
    <div class="slider_dots_container">
        <span :class="{ 'dotActive': index === activeSlider }" 
               class="slider_dots_dot" 
               v-for="(slider, index) in slidersCount" 
               :key="index" 
               @click="goToSlider(slider)"></span>
    </div>
</section>
</template>
<!--SCRIPTS-->
<script>
import { mapState, mapActions } from 'vuex'
export default {
name: 'MainSlider',

computed:{
    ...mapState('MainSlider', ['activeSlider', 'slidersCount']),
},

mounted() {
    console.log(this.$options.name+' component successfully mounted');
    this.startSlider();
},

methods:{
    ...mapActions('MainSlider', ['nextSlider', 'prevSlider']),
}
};
</script>

And here is my Slider Store:

//STATE
const state = {
  slidersCount: 3,
  sliderInterval: 3000,
  activeSlider: 1,

}

//GETTERS
const getters = {

}

//ACTIONS
const actions = {


    prevSlider ({ commit, state }) {
        if(state.activeSlider == 1){
            commit( 'TO_LAST_SLIDER' );
        }
        else{
            commit( 'PREV_SLIDER' );
        }
    },


    nextSlider ({ commit, state }) {
        if(state.activeSlider == state.slidersCount){
            commit( 'TO_FIRST_SLIDER' );
        }
        else{
            commit( 'NEXT_SLIDER' );
        }
    },


    goToSlider ({ commit, sliderIndex }) {
        commit('GO_TO_SLIDER', sliderIndex)
        
    },



}

//MUTATIONS
const mutations = {


    PREV_SLIDER (state) {
        state.activeSlider--;
    },

    NEXT_SLIDER (state) {
        state.activeSlider++;
    },

    GO_TO_SLIDER (state, sliderIndex) {
        state.activeSlider = sliderIndex;
    },

    TO_FIRST_SLIDER (state) {
        state.activeSlider = 1;
    },

    TO_LAST_SLIDER (state) {
        state.activeSlider = state.slidersCount;
    },


}

export default {
    namespaced: true, state, getters, actions, mutations
  }

I realize that this could be simplified by associating each DOM slider with an object and using a v-for loop. However, as far as I know, I cannot do this with raw DOM elements since I am not fetching the slider images from a backend source.

Answer №1

If you want to achieve this effect, you can do the following:

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

Essentially, you are incorporating JavaScript logic within the curly braces {}. Remember to use ":" when binding :class.

For more information on class and style binding in Vue.js, check out: https://v2.vuejs.org/v2/guide/class-and-style.html

Answer №2

To achieve the activation of the dotActive class for a specific span based on the matching of activeSlider with the span's index, you can utilize a class binding in your Vue.js template:

<span v-for="slider in sliderCount"
      :class="{ dotActive: slider === activeSlider }">

new Vue({
  el: '#app',
  data() {
    return {
      activeSlider: 1,
      sliderCount: 3
    };
  },
  methods: {
    slide(diff) {
      let slider = (this.activeSlider + diff) % (this.sliderCount + 1);

      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.6.14"></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>

Answer №3

Implementing class binding is simple:

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

The variable 'isActive' determines if the class 'active' is applied or not.

This code snippet is sourced from Vue.js's official documentation available at www.vuejs.org

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How is it possible for the javascript condition to be executed even when it is false?

Despite the condition being false, the javascript flow enters the if condition. Check out the code snippet below: <script> $(document).ready(function() { var checkCon = "teststr2"; console.log("checkCon: "+checkCon); if(checkCon == " ...

Scroll through the carouFredSel carousel by pressing the mouse

Looking to create a carousel that continuously scrolls when the mouse is pressed down and stops when released. Currently have a working example with hover functionality. How can I modify it to work based on mousedown instead? $("#foo2").carouFredSel({ ...

The application experiences a sudden failure when Mongoose is unable to locate the specified item

I am facing an issue where my app crashes when mongoose is unable to find the item. I want to display a 404 error page instead. Here is the code snippet: try { let theBeverage = Product.findOne({ _id: beverageId }); await theBeverage.then((data) ...

Connection Error: Unable to Resolve Host Name socketIO

the issue I am facing is as follows: GET net::ERR_NAME_NOT_RESOLVED I have implemented an environment variable named VUE_APP_BACKEND_API using vuecli3 for the ip address. In addition to Vue.js, I am also utilizing VueSocketIO. I am unsure of the source ...

Using the method window.open() will launch a new window instead of opening a new tab

When the page loads, I am using JavaScript to call window.open. window.open(url, "Test Page"); Initially, it opens a new Chrome window and displays the page. However, when I use the same JavaScript code after the page has loaded, it opens the page in a n ...

Utilizing API data to set the state in a React component

In my quest to modify the state of this React component, I have a variable called rankAndTeam that holds the "prints=>" data listed below. My goal is to assign "Washington Capitals" to this.state.teamRank["0"], "New York Islanders" to this.state.teamRan ...

I'm having trouble getting my placeholder to display correctly in react-native-datepicker. What could be the issue?

I'm struggling with displaying a placeholder correctly in the datepicker package I'm utilizing for react native... This is how I've configured the component: The _onDateChange function: const _onDateChange = (startTime) => { pickDa ...

After successful login, the user will be automatically directed to the next page with

I am encountering challenges with a specific portion of my code. I am in the process of sending user information to the server, receiving a token from the user, and then aiming to redirect the user to a URL. However, despite the code entering the if stat ...

How to send route parameters to a controller function in ExpressJS

I'm currently working on setting up user authentication for my application using passport JS. I am facing a challenge in passing the passport variable between app.js, routes.js, and controller.js. Despite trying various approaches, I have been unsucce ...

The Transparent Quirk in Three.js

Hey there! I'm working on displaying a 3D avatar on my website that allows users to apply textures to the character. I'm hoping to enable users to create transparent textures so they can see the model underneath. Right now, when implementing tran ...

Utilize Jquery to interact with Android's date picker interface

Currently, I am developing an application for IOS and Android using Phonegap with Cordova 2.2.0. In my development process, I am utilizing jQuery and HTML5 technologies. While working on the IOS version, I found that simply setting the input type to "dat ...

The skybox in Three.js functions perfectly when scaled small, but mysteriously turns black when scaled

After successfully creating a skybox with the provided code, I ran into an issue where it displayed perfectly at 1,000 x 1,000 x 1,000 dimensions. However, upon expanding it to 10,000 x 10,000 x 10,000, it only appeared as black. Is there a specific sett ...

"Sorry, but window.print function is not available in this environment

Whenever I try to execute something in jest, I keep encountering the same error message: console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29 Error: Not implemented: window.alert at module.expor ...

Encountering a deployment issue on Vercel while building with NextJS

I'm facing issues while attempting to deploy my Nextjs app on Vercel: Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error TypeError: (0 , react_development_.useState) is not a function or its ret ...

What is the process for executing a Js file on a website?

I am looking to automate some tasks on a website that I do not own. Specifically, I need to automatically fill out a form and perform certain clicking actions. Can JavaScript be used for this purpose? I am unsure how to run a .js file on a site without the ...

When attempting to upload a picture using the camera, the file upload process is unsuccessful

Whenever I attempt to upload an image from my existing files, everything goes smoothly. However, if I try to select a file by directly clicking on the camera icon on my mobile device, it fails with a "CORS Error" message. I have tried adding and removing t ...

The toggle function for the hamburger icon is currently malfunctioning

I am facing an issue with the hamburger icon on my website. The toggle functionality associated with it is not working properly. Even though I have a class named change-1 that should be toggled upon clicking the icon, it is not happening. There are no erro ...

Using an array with the useState React hook may lead to some render calls being skipped

I am facing an issue with the following code snippet: function MyComponent( props ) { let arrSize = 5; const [arr, setArr] = useState( () => { let initial = new Array(arrSize); for(let i=0; i<arrSize; i++) initial.push({ foo: ...

"Streamlining communication: Building a mail sending form with AJAX, JQuery

I am currently dealing with a dilemma on my website where I have 2 contact forms, and I am utilizing ajax jQuery to send emails via PHP. Everything works smoothly when I use a single form along with jQuery. However, when I try to adapt the jQuery code for ...

A guide on converting character objects to strings

Presented below is an array of characters: Resource {0: "-", 1: "-", 2: "-", 3: "-", 4: "-", 5: "B", 6: "E", 7: "G", 8: "I", 9: "N", 10: " ", 11: "C", 12: "E", 13: "R", 14: "T", 15: "I", .... } I am looking to convert it into the following format: --- ...