vue移动端长按事件实现的几种方法总结

在vue中长按事件并没有封装,在使用的时候需要我们自己取写一个方法获取长按事件。

方法一:使用@touchstart,@touchend,

start () {

      clearTimeout(this.loop); //再次清空定时器,防止重复注册定时器

      this.loop = setTimeout(() => {

        console.log("长按了");

      }, 1000);

    },

 end () {

      clearTimeout(this.loop); //清空定时器,防止重复注册定时器

    },

备注:使用的时候注意如果是图片,建议把图片设置为背景,直接使用图片,在长按时会触发浏览器对图片的保存、分享等。

方法二:

// 指令

export default {

  install(Vue, options = {

    time: 2000,

  }) {

    Vue.directive('longpress', {

      bind: function(el, binding, vNode) {

        if (typeof binding.value !== 'function') {

          const compName = vNode.context.name

          let warn = `[longpress:] provided expression '${binding.expression}' is not afunction, but has to be `

          if (compName) { warn += `Found in component '${compName}' ` }

          console.warn(warn)

        }

        // 定义变量

        let pressTimer = null

        // 定义函数处理程序

        // 创建计时器( 1秒后执行函数 )

        let start = (e) => {

          if (e.type === 'click' && e.button !== 0) {

            return

          }

          if (pressTimer === null) {

            pressTimer = setTimeout(() => {

              // 执行函数

              handler()

            }, options.time)

          }

        }

        // 取消计时器

        let cancel = (e) => {

          // 检查计时器是否有值

          if (pressTimer !== null) {

            clearTimeout(pressTimer)

            pressTimer = null

          }

        }

        // 运行函数

        const handler = (e) => {

          // 执行传递给指令的方法

          binding.value(e)

        }

        // 添加事件监听器

        el.addEventListener('mousedown', start)

        el.addEventListener('touchstart', start)

        // 取消计时器

        el.addEventListener('click', cancel)

        el.addEventListener('mouseout', cancel)

        el.addEventListener('touchend', cancel)

        el.addEventListener('touchcancel', cancel)

      },

    })

  },

}

方法三:vue自定义手势

       如果给父元素添加v-longTap事件,点击子元素时无法触发点击事件。

以上三种方法,按需使用,在使用中有什么疑问可以私信我。

你可能感兴趣的:(vue移动端长按事件实现的几种方法总结)