You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js中如何实现按住鼠标按钮持续递增数值的功能

Vue按住鼠标按钮持续递增数值实现方案

核心思路

mousedown事件仅会在按下瞬间触发一次,因此需要在按下时启动周期性定时器持续执行递增逻辑,松开鼠标/鼠标移出按钮时销毁定时器即可。

具体实现步骤

1. 扩展data定义,新增定时器存储变量

data() {
  return {
    robotx_pos_number: 0,
    // 存储递增定时器ID,用于后续销毁
    increaseTimer: null
  }
},

2. 封装事件处理方法,替换行内逻辑

methods: {
  // 按下时触发的逻辑
  startIncrease() {
    // 先执行一次递增,避免按下后有操作延迟
    this.robotx_pos_number++
    this.setValue({
      name: 'robotx_increase',
      value: 'true'
    })
    // 启动定时器,每100ms递增一次,间隔可自行调整
    this.increaseTimer = setInterval(() => {
      this.robotx_pos_number++
    }, 100)
  },
  // 松开/移出按钮时触发的逻辑
  stopIncrease() {
    this.setValue({
      name: 'robotx_increase',
      value: 'false'
    })
    // 销毁定时器,避免内存泄漏和无效累加
    if (this.increaseTimer) {
      clearInterval(this.increaseTimer)
      this.increaseTimer = null
    }
  }
}

3. 修改button的事件绑定

<button
  @mousedown="startIncrease"
  @mouseup="stopIncrease"
  @mouseleave="stopIncrease"
>
</button>

可调参数说明

  • 可以修改setInterval的第二个参数(单位毫秒)调整递增速度,数值越小速度越快
  • 如果需要支持自定义增量步长,可把robotx_pos_number++改成robotx_pos_number += 自定义步长值即可

内容的提问来源于stack exchange,提问作者veritas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 08:15:03