Home > Software engineering >  toggle class on click Vue3
toggle class on click Vue3

Time:04-07

I want to toggle a class on click, but something does not work here.

<script setup>
import { ref } from "vue";

let isOpen = ref(false);

const openMenu = () => {
  isOpen = !isOpen;
  console.log(isOpen);
};
</script>


<template>
  <div >
    <div  @click="openMenu">
      <span :></span>
      <span :></span>
    </div>
  </div>
</template>

What did I do wrong? isOpen is actually changed by the click, but not the class.

CodePudding user response:

isOpen is a ref, so you have to unwrap it with .value:

<script setup>
import { ref } from 'vue';
let isOpen = ref(false);

// isOpen = !isOpen; ❌
isOpen.value = !isOpen.value; ✅
</script>

demo 1

Alternatively, you could use the Reactivity Transform to avoid having to unwrap:

<script setup>
//import { ref } from 'vue';
//let isOpen = ref(false);
let isOpen = $ref(false); ✅

isOpen = !isOpen;
</script>

demo 2

CodePudding user response:

<template>
  <div >
    <div  @click="openMenu">
      <span :></span>
      <span :></span>
   </div>
 </div>  <-----
</template>

You're missing that end tag. Could it be that?

  • Related