Vue自定义指令实现拖拽效果

Vue提供了自定义指令的方法,使得功能更加丰富,现在就用Vue提供的自定义指令实现拖拽。
先看效果:
在这里插入图片描述
自定义指令,可以实现指令的复用,上代码:

Vue.directive("drag", {   					//指令的名称
	inserted: function (el, binding) {		//当被绑定的元素插入到 DOM 中时
	    el.style.position = "absolute";
	    el.style.left = binding.arg.left + "px";
	    el.style.top = binding.arg.top + "px";
	    el.onmousedown = function (e) {
	        var x = e.offsetX;
	        var y = e.offsetY;
	        document.onmousemove = function (eve) {
	            el.style.left = eve.clientX - x + "px";
	            el.style.top = eve.clientY - y + "px";
	        }
	        document.onmouseup = function () {
	            document.onmousemove = null;
	            document.onmouseup = null;
	        }
	    }
}

使用方法:

<div class="app" v-drag:[office]></div>								//使用:[]方法可以传递多个参数
var vm = new Vue({
	el:"",							//Dom源
	data:{
		office:{
			left:100,
			top:200
		}
	}
})

上述指令可以放在任意标签上复用

猜你喜欢

转载自blog.csdn.net/qq_40375518/article/details/107559750