Philip F.
Philip F.

Reputation: 1237

How to toggle event if class is active vue3

Question

I want to toggle an event if the 'active' class gets added to an element. How can I achieve this?

In my opinion it could be somehow achieved with a watcher method but I don't know how to watch if a classname applies on an element.

I'm using vue3.

Edit

I have a carousel, where you can slide through some divs and the visible gets the class 'active'. I want to watch all divs, and if they get active call a function.

Upvotes: 2

Views: 913

Answers (1)

Matt
Matt

Reputation: 10312

Here's an example of achieving this in a declarative way.

const { watch, ref } = Vue;

const CarouselItem = {
    props: ['item'],

    template: `<h1 :class="{ ...item }">{{ item.name }}</h1>`,

    setup(props) {
        watch(
            props.item,
            (item, prevItem) => item.active && console.log(`${item.name} made active!`),
        );
    }
};

Vue.createApp({
    components: { CarouselItem },

    template: '<CarouselItem v-for="item in items" :item="item" />',

    setup() {
        const items = ref([
            { name: 'Doril', active: false },
            { name: 'Daneo', active: false },      
            { name: 'Mosan', active: false },
        ]);

        // simulate a carousel item being made active
        setTimeout(() => items.value[1].active = true, 1000);

        return { items };
    },
}).mount('#app');
.active {
    color: red;
}
<script src="https://unpkg.com/[email protected]/dist/vue.global.js"></script>

<div id="app"></div>

Upvotes: 2

Related Questions