TheCallofDuty
TheCallofDuty

Reputation: 153

Vue3: Toggle Class on Click

Yesterday I started working with Vue and have already learned quite a bit. Now I have seen, you can toggle classes directly on the HTML object via the @click event.

Unfortunately, I do not really succeed. With Blank Javascript no problem, but I want to implement this with Vue.

<li @click=" show = !show" :class="{ active: show }" class="nav-item dropdown">

setup() {
    const show = false

    return { show };
},

In this is "show" the class which i want to toggle.

Upvotes: 1

Views: 3568

Answers (1)

kissu
kissu

Reputation: 46604

This may be working fine

<script>
import { ref } from 'vue'

export default {
  setup() {
    const show = ref(false)
    return { show }
  }
}
</script>

<template>
  <li @click="show = !show" :class="{ active: show }" class="nav-item dropdown">toggle me</li>
</template>

<style>
  .active {
    background-color: red;
  }
</style>

Playground link


This is also a valid syntax btw

<script setup>
import { ref } from 'vue'

const show = ref(false)
</script>

You can also use :class="show && 'active'" if you prefer to not have to invert/think of the actual order every-time (personal preference, exactly the same at the end).

Upvotes: 1

Related Questions