vue 实现鼠标放上后显示,挪开后隐藏(点击显示/隐藏)
在Vue中实现鼠标悬停显示、移出隐藏的效果,可以通过以下两种常用方式实现:
1、原生事件绑定方案(适合简单交互)
<template><div><div @mouseenter="isShow = true" @mouseleave="isShow = false"class="hover-area">鼠标移入这里</div><div v-show="isShow" class="content-box">这是要显示隐藏的内容</div></div>
</template><script>
export default {data() {return {isShow: false}}
}
</script><style>
.hover-area {padding: 10px;background: #f0f0f0;cursor: pointer;
}
.content-box {margin-top: 10px;padding: 15px;background: #e1f5fe;
}
</style>
这段代码通过mouseenter/mouseleave事件控制显示状态,适合基础交互场景。
2、组件封装方案(推荐复用)
<template><div class="hover-wrapper"><div @mouseenter="handleMouseEnter"@mouseleave="handleMouseLeave"class="trigger"><slot name="trigger"></slot></div><transition name="fade"><div v-show="isVisible" class="tooltip-content"><slot name="content"></slot></div></transition></div>
</template><script>
export default {data() {return {isVisible: false}},methods: {handleMouseEnter() {this.isVisible = true},handleMouseLeave() {this.isVisible = false}}
}
</script><style>
.hover-wrapper {position: relative;display: inline-block;
}
.tooltip-content {position: absolute;z-index: 100;padding: 8px 12px;background: #333;color: white;border-radius: 4px;
}
.fade-enter-active, .fade-leave-active {transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {opacity: 0;
}
</style>
这个组件采用插槽设计,支持自定义触发元素和内容,添加了过渡动画效果,适合项目复用。使用时通过slot分别传入触发区域和悬浮内容即可
3、点击事件完成切换
<template slot-scope="scope"><div><div v-show="!isShow"@click="showpaperpass"class="hover-area">隐藏时的内容</div></div><div v-show="isShow" class="content-box">显示的内容</div> </template><script>
export default {data() {return {isShow: false}},methods: {showpaperpass() {this.isShow = truesetTimeout(() => {this.isShow = false}, 7000); // 7秒后隐藏 },}
}
</script>
<style>
.hover-area {padding: 10px;background: #f0f0f0;cursor: pointer;
}
.content-box {margin-top: 10px;padding: 15px;background: #e1f5fe;
}
</style>