vue实现 hover
Vue 实现 hover 效果的方法
在 Vue 中实现 hover 效果可以通过多种方式完成,以下是常见的几种方法:
使用 CSS 伪类
通过 CSS 的 :hover 伪类直接实现 hover 效果,这是最简单的方式。在 Vue 的 <style> 块中直接编写 CSS 规则即可。
.button:hover {
background-color: #42b983;
color: white;
}
使用 Vue 的动态 class 绑定
通过 Vue 的 v-bind:class 或简写 :class 动态绑定类名,结合鼠标事件来控制 hover 状态。
<template>
<button
@mouseover="isHovered = true"
@mouseleave="isHovered = false"
:class="{ 'hover-effect': isHovered }"
>
Hover me
</button>
</template>
<script>
export default {
data() {
return {
isHovered: false
};
}
};
</script>
<style>
.hover-effect {
background-color: #42b983;
color: white;
}
</style>
使用 Vue 的动态 style 绑定
通过 v-bind:style 或简写 :style 直接动态绑定内联样式,适合需要动态计算样式的场景。
<template>
<button
@mouseover="hoverStyle = { backgroundColor: '#42b983', color: 'white' }"
@mouseleave="hoverStyle = {}"
:style="hoverStyle"
>
Hover me
</button>
</template>
<script>
export default {
data() {
return {
hoverStyle: {}
};
}
};
</script>
使用第三方库(如 VueUse)
如果需要更复杂的交互效果,可以使用 @vueuse/core 提供的 useMouse 或自定义逻辑。
<template>
<button
@mouseover="startHover"
@mouseleave="endHover"
:style="{ backgroundColor: hoverColor }"
>
Hover me
</button>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const hoverColor = ref('');
const startHover = () => {
hoverColor.value = '#42b983';
};
const endHover = () => {
hoverColor.value = '';
};
return { hoverColor, startHover, endHover };
}
};
</script>
使用 CSS 变量和 Vue 结合
通过 Vue 动态更新 CSS 变量,实现 hover 效果。
<template>
<button
@mouseover="setHover"
@mouseleave="resetHover"
class="hover-button"
>
Hover me
</button>
</template>
<script>
export default {
methods: {
setHover() {
document.documentElement.style.setProperty('--hover-bg', '#42b983');
},
resetHover() {
document.documentElement.style.setProperty('--hover-bg', '');
}
}
};
</script>
<style>
.hover-button:hover {
background-color: var(--hover-bg);
color: white;
}
</style>
总结
- 纯 CSS:适合简单的 hover 效果,无需 JavaScript。
- 动态 class/style:适合需要与组件状态联动的场景。
- 第三方库:适合复杂交互或需要复用逻辑的情况。
- CSS 变量:适合需要全局控制样式的场景。







