vue-directive自定义指令实现拖拽

vue拥用很多强大的指令,但有些逻辑无法实现,所以vue提供了directive自定义指令由开发者任意扩展,本文自定义一个拖拽功能的指令

一、效果图如下

二、指令的使用:自定义拖拽的初始位置(left,top),不传参默认为0,即在左上角


三、思路解析

1、首先需要清楚指令里面有哪些参数,第一个参数el是绑定元素

2、第二个参数一个对象(包含指令name,value,argument等),绑定指令那里传参,这里接收参数并写逻辑

四、附上具体实现代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 120px;
            height: 120px;
            background-color: #eee;
        }
    </style>
</head>

<body>
</body>
<div id="app">
    <button v-drag>点击</button>
    <div class="box" v-drag:[place]></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>

    Vue.directive('drag', {
        inserted: function (el, bancing) {
            console.log(bancing)**
            if (bancing.arg) {
                **l = bancing.arg.left;
                t = bancing.arg.top;
            } else {**
                l = t = 0;**
            }**
            el.style.position = 'absolute';
            **el.style.left = l + 'px';
            el.style.top = t + 'px';
            el.onmousedown = function (e) {
                var x = e.offsetX;
                var y = e.offsetY;
                document.onmousemove = function (eve) {
                    var left = eve.clientX - x;
                    var top = eve.clientY - y;
                    el.style.left = left + 'px';
                    **el.style.top = top + 'px';**
                }
                document.onmouseup = function (eve) {**
                    document.onmousemove = null;**
                    document.onmouseup = null;**
                }
            }
        }
    })
    new Vue({
        el: '#app',
        data: {
            place: {
                left: 100,
                top: 100
            }
        }
    })
</script>

</html>
posted @ 2020-07-24 13:19  飘逸_winxin  阅读(1018)  评论(0编辑  收藏  举报