- main.js文件中添加已下代码
Vue.directive('drag', {bind: function (el) { },inserted: function (el) {let odiv = el; let firstTime = '', lastTime = '';el.onmousedown = function (e) {var disx = e.pageX - el.offsetLeft;var disy = e.pageY - el.offsetTop;odiv.setAttribute('ele-flag', false)odiv.setAttribute('draging-flag', true)firstTime = new Date().getTime();document.onmousemove = function (e) {el.style.left = e.pageX - disx + 'px';el.style.top = e.pageY - disy + 'px';}document.onmouseup = function (event) {document.onmousemove = document.onmouseup = null;lastTime = new Date().getTime();if ((lastTime - firstTime) > 200) {odiv.setAttribute('ele-flag', true)event.stopPropagation()}setTimeout(function () {odiv.setAttribute('draging-flag', false)}, 100)}}}
})
- 组件中的使用
<template><div class="drag" v-drag @click="handleDragClick"> 我是拖拽的div<div>
<template>
<script>methods:{handleDragClick(e){let isDrag = false;try {isDrag = e.target.getAttribute('ele-flag') === 'true';}catch (e) {}if(isDrag){return;}}
}
</script>
<style>
.drag{width:100px;height:100px;border:1px solid pink;
}
</style>