Nuxt Composition API:悬停时更改 class

Nuxt Compostion API: Change class on hover

<script setup>

import Logo from "../assets/svgs/Logo";
import Menu from "../assets/svgs/Menu";

const hover = Boolean
let boxTop

if (hover === true) {
  boxTop = 'boxTop--0'
} else {
  boxTop = 'boxTop--20'
}

</script>

<template>
  <nav class=" w-full fixed flex items-center">
    <div class="w-full flex h-full">
      <div class="px-6 flex items-center justify-center h-full relative "
           @mouseover="hover = true" @mouseleave="hover = false"
      >
        <Menu class="w-10 fill-white"/>

        <div class="absolute w-full h-full bg-black" :style="boxTop"></div>
      </div>
    </div>
  </nav>
</template>

我想做到这一点,当鼠标进入 div 时,添加 css class "boxTop--0",当鼠标离开 div,添加 css class "boxTop--20"。但是,我不知道如何使用合成 api.

如有任何帮助,我将不胜感激。

请查看以下代码段: 您可以使用 ref 创建反应状态 (boxTop) 并创建用于更改状态的函数。

const { ref } = Vue
const app = Vue.createApp({
  el: "#demo",
  setup() {
    const boxTop = ref(null)
    const hover = (val) => {
      if (val) {
        boxTop.value = 'boxTop--0'
      } else {
        boxTop.value = 'boxTop--20'
      }
    }
    return { boxTop, hover }
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3"></script>
<div id="demo">
  <nav class=" w-full fixed flex items-center">
    <div class="w-full flex h-full">
      <div class="px-6 flex items-center justify-center h-full relative "
           @mouseenter="hover(true)" @mouseleave="hover(false)"
      >
        hover me
        <div class="absolute w-full h-full bg-black" :style="boxTop">
        {{ boxTop }}
        </div>
      </div>
    </div>
  </nav>
</div>

像这样的东西应该可以解决问题,使用 computed

<script setup>
import Menu from "../assets/svgs/Menu"

const hover = ref(true)
const boxTop = computed(() => hover.value ? 'boxTop--0' : 'boxTop--20')
</script>

<template>
  <nav class="fixed flex items-center w-full">
    <div class="flex w-full h-full">
      <div class="relative flex items-center justify-center h-24 h-full px-6 bg-green-500" @mouseover="hover = true" @mouseleave="hover = false">
        <Menu class="w-10 fill-white" />

        <div class="absolute w-full h-full bg-black" :class="boxTop"></div>
      </div>
    </div>
  </nav>
</template>

<style scoped>
.boxTop--0 {
  background-color: red;
}
.boxTop--20 {
  background-color: teal;
}
</style>

我已经使用 :class="boxTop" 和一些 类 来帮助我调试您尝试过的内容。