拖拽
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('只触发一次')
}
},