vue中使用@mousedown、@mouseenter等鼠标事件失效解决办法

在 Vue 框架中,使用 @click 事件处理点击无误,但遇到 @mouseenter 和 @mousedown 等非点击事件时,事件监听失效。解决方法是在非点击事件上添加 .native修饰符,如 @mouseenter.native,以确保在组件元素上正确触发。此问题涉及到 Vue 的事件绑定机制和事件修饰符的使用。

在vue中,使用@click点击事件没有任何问题

 <el-button type="primary" icon="el-icon-plus" @click="searchBtn">添加用户</el-button>

但是将@click替换为@mouseenter、@mousedown等鼠标事件[非鼠标点击事件]时,发现事件不触发(也就是失效了)

此时应该在@mouseenter、@mouseenter等鼠标事件加上native属性就好了

 <el-button type="primary" icon="el-icon-plus" @mouseenter.native="searchBtn">添加用户
</el-button>

 

<div class="image-container" @click="handelAi" @mouseenter="currentImg = hoverImg" @mouseleave="showDefaultImg" @mousedown="startDrag" :style="containerStyle" > <img :src="currentImg" alt="切换图片" class="ratio-img"> </div> handelAi(){ ticket().then(res=>{ window.open(res.url) }) } , setInitialPosition() { // 获取容器DOM元素 // 1. 获取视口宽高(不含滚动条) const viewportWidth = document.documentElement.clientWidth; const viewportHeight = document.documentElement.clientHeight; // // 4. 计算初始left和top,实现右下角定位 this.containerLeft = viewportWidth - 400; this.containerTop = viewportHeight - 500; }, startDrag(e) { // 阻止默认行为(避免拖动时选中文本) e.preventDefault(); // 标记开始拖动 this.isDragging = true; // 记录鼠标按下时的坐标(相对于浏览器窗口) this.startX = e.clientX; this.startY = e.clientY; // 记录容器当前的left和top(初始位置,后续拖动基于此计算偏移) this.initialLeft = this.containerLeft; this.initialTop = this.containerTop; // 绑定鼠标移动和松开事件(监听document,避免鼠标移出容器后失效) document.addEventListener('mousemove', this.handleDrag); document.addEventListener('mouseup', this.endDrag); }, // 2. 鼠标移动:计算拖动距离,更新容器位置 handleDrag(e) { if (!this.isDragging) return; // 未拖动时不执行 // 计算鼠标移动的偏移量(当前位置 - 初始位置) const offsetX = e.clientX - this.startX; const offsetY = e.clientY - this.startY; // 更新容器位置(初始位置 + 偏移量) this.containerLeft = this.initialLeft + offsetX; this.containerTop = this.initialTop + offsetY; }, // 3. 鼠标松开:结束拖动,移除事件监听 endDrag() { this.isDragging = false; // 移除document上的事件监听(避免内存泄漏) document.removeEventListener('mousemove', this.handleDrag); document.removeEventListener('mouseup', this.endDrag); }, 我拖动后 会触发点击事件怎么解决冲突
最新发布
10-21
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值