<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 >
<div >
<div
@mouseover="hover = true" @mouseleave="hover = false"
>
<Menu />
<div :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.
CodePudding user response:
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 >
<div >
<div
@mouseenter="hover(true)" @mouseleave="hover(false)"
>
hover me
<div :style="boxTop">
{{ boxTop }}
</div>
</div>
</div>
</nav>
</div>
CodePudding user response:
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 >
<div >
<div @mouseover="hover = true" @mouseleave="hover = false">
<Menu />
<div :></div>
</div>
</div>
</nav>
</template>
<style scoped>
.boxTop--0 {
background-color: red;
}
.boxTop--20 {
background-color: teal;
}
</style>
I've used :
and some classes to help me debug what you have tried.