Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

toggle class on click Vue3

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 class="nav">
    <div class="nav_burger" @click="openMenu">
      <span :class="isOpen ? 'top-line' : '' "></span>
      <span :class="isOpen ? 'bottom-line' : '' "></span>
    </div>
  </div>
</template>

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading