单击 Vue3 时切换 class

toggle class on click Vue3

我想在点击时切换 class,但这里有些东西不起作用。

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

我做错了什么? isOpen实际上是通过点击改变的,而不是class。

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

您缺少结束标记。难道是那个?

isOpen 是一个 ref,所以你必须用 .value:

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

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

demo 1

或者,您可以使用 Reactivity Transform 来避免解包:

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

isOpen = !isOpen;
</script>

demo 2