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 = true
      setTimeout(() => {
        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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值