'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>
I want to make it so when the mouse enters the div, the css class "boxTop--0" gets added, and, when the mouse leaves the div, the css class "boxTop--20" gets added. However, I can't figure out how to do it with compositon api.
I would be very greatful for any help.
Solution 1:[1]
Please take a look at following snippet:
You can create reactive state (boxTop
) with ref
and create function for changing state.
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>
Solution 2:[2]
Something like this should do the trick, using a 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>
I've used :class="boxTop"
and some classes to help me debug what you have tried.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | kissu |