1

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.

3
  • You must declare your variable like const show = ref(false) to make it reactive (and Vue re-render the template whenever it changes) Commented Mar 27, 2022 at 9:55
  • @MichalLevý thanks for your answer but "ref is not defined" Commented Mar 27, 2022 at 9:57
  • Read the documentation! Commented Mar 27, 2022 at 11:11

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

3 Comments

It works thanks! And how do I set this up, if I want to toggle the class "show" to another element when I click on the LI element ?
@TheCallofDuty not sure to totally understand. But if you want to have several elements with their own state, you will probably need to have an array of objects and toggle the state in each of those objects. If I misunderstood, feel free to correct me and provide a use-case.
i got here my <li @click... :class ...> and here another <div></li> How it is possible to set after klick on <li> the class show to the another <div> inside the li ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.