vue自定义拖拽指令和函数防抖指令

拖拽

1.新建draggable.js文件,代码如下:

import Vue from 'vue'

Vue.directive('draggable', {
  inserted: function(el) {
    el.style.cursor = 'move'
    el.onmousedown = function(e) {
      let disx = e.pageX - el.offsetLeft
      let disy = e.pageY - el.offsetTop
      document.onmousemove = function(e) {
        let x = e.pageX - disx
        let y = e.pageY - disy
        let maxX = document.body.clientWidth - parseInt(window.getComputedStyle(el).width)
        let maxY = document.body.clientHeight - parseInt(window.getComputedStyle(el).height)
        if (x < 0) {
          x = 0
        } else if (maxX > 0 && x > maxX) {
          x = maxX
        }

        if (y < 0) {
          y = 0
        } else if (maxY > 0 && y > maxY) {
          y = maxY
        }
        el.style.left = x + 'px'
        el.style.top = y + 'px'
      }
      document.onmouseup = function() {
        document.onmousemove = document.onmouseup = null
      }
    }
  }
})

2.在main.js中引用

import "./directive/draggable";

3.在组件中使用,设置需要拖拽的元素为相对定位,其父元素为绝对定位

<template>
	<div class="animation-box">
	    <div class="drage-box" v-draggable>
	      <h3>可拖拽的弹框</h3>
	      <div>
	        <p>内容</p>
	      </div>
	    </div>
	
	  </div>
</template>
<script>
export default {
 data() {
    return {
    };
  },
};
</script>
<style scoped lang="less">
  .animation-box{
    background-color: black;
    color: white;
    position: absolute;
    .drage-box{
      position: relative;
      top: 150px;
      left: 600px;
      width: 200px;
      height: 300px;
      text-align: center;
      border: 1px solid cyan;
      h3{
        height: 50px;
        line-height: 50px;
        border-bottom: 1px solid cyan;
        //文字不可被选中
        -webkit-user-select:none;
        -moz-user-select:none;
        -ms-user-select:none;
        user-select:none;
      }
    }
  }
</style>

函数防抖

1.新建debounce.js文件,代码如下:

import Vue from 'vue'

Vue.directive('debounce', {
  inserted: function (el, binding) {
    let timer
    el.addEventListener('click', () => {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        binding.value()
      }, 1000)
    })
  }
})

2.在main.js中引用

import "./directive/debounce";

3.在按钮中使用

<button v-debounce="debounceClick">提交</button>

 methods: {
    debounceClick () {
      console.log('只触发一次')
    }
  },

参考https://juejin.cn/post/6906028995133833230#heading-7

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值