vue 自定义指令 拖拽

之前看别人vue的视频,练习写了个自定义指令-拖拽,当时引入vue.js的版本是1.0.28,现在也可以正常使用。上代码

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>vue 指令 -拖拽</title>
	<script src="vue.js"></script>
	<style>
	#box{width: 100px;height: 100px;background: blue;position: absolute;left: 0;top: 0}
	</style>
</head>
<body>
	<div id="box" v-drag></div>
	<script>
	Vue.directive('drag',function(){
		console.log('this:',this);//Directive
		var oDiv = this.el;
		oDiv.onmousedown = function(ev){
			var ev = ev || window.event;
			var disX = ev.clientX-oDiv.offsetLeft;
			var disY = ev.clientY-oDiv.offsetTop;


			document.onmousemove = function(ev){
				var l = ev.clientX-disX;
				var t = ev.clientY-disY;
				oDiv.style.left = l+'px';
				oDiv.style.top = t+'px';
			};
			document.onmouseup = function(){
				document.onmousemove = null;
				document.onmouseup = null;
			}
		};
		
	});
	new Vue({
		el: '#box',
		data:{
		}
	});
	</script>
</body>
</html>

两点注意:Vue.directive()指令一定要在vue实例创建之前,dom元素一定要设置绝对定位。

现在用2.0版本就不好使了,去看了下文档,修改了一下。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title></title>
    <link rel="stylesheet" href="">
    <script src="./vue.js"></script>
    <style>
        .drag{
            position: absolute;
            width: 200px;
            height: 200px;
            background: yellowgreen
        }
    </style>
    <script>
        Vue.directive('drag',
          {bind: function(el){
            var oDiv = el;//el就是指令绑定的元素
            oDiv.onmousedown = function(ev){
                var startX = ev.clientX - oDiv.offsetLeft;
                var startY = ev.clientY - oDiv.offsetTop;

                document.onmousemove = function(e){
                    oDiv.style.left = (e.clientX - startX==0)? 0 : e.clientX - startX+ 'px';
                    oDiv.style.top = e.clientY - startY==0? 0: e.clientY - startY + 'px';
                    
                }

                document.onmouseup = function () {
                    document.onmousemove = null;
                    document.onmouseup = null
                }
            }
        }})
        window.onload = function(){
            var vm = new Vue({
                el: '#app',
                data:{
                    
                }
            })
        }
    </script>
</head>
<body>
    <div id="app">
        
        <div class="drag" v-drag></div>
    </div>
</body>
</html>

文档地址:https://cn.vuejs.org/v2/guide/custom-directive.html

边界检测什么的还没有做,先记下来

上一篇:使用VSS2005的时候报错:输入正确的服务器地址依然出错了


下一篇:JavaScrip事件