Vue实现开关按钮拖拽效果

时间:2022-12-08 11:10:32

本文实例为大家分享了Vue实现开关按钮拖拽效果的具体代码,供大家参考,具体内容如下

css:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<style>
  .box {
    position: absolute;
    left: 100px;
    top: 100px;
    width: 100px;
    height: 100px;
    background: red;
  }
  .box2 {
    position: absolute;
    left: 400px;
    top: 100px;
    width: 100px;
    height: 100px;
    background: green;
  }
</style>

html:

?
1
2
3
4
5
6
7
8
9
<div id="app">
 
  <div class="box" v-drag="isDrag"></div>
 
  <div class="box2" v-drag:fn.limit.b="isDrag"></div>
 
  <button @click="isDrag = !isDrag">{{isDrag}}</button>
 
</div>

js:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<script src="vue.js"></script>
<script>
 
  // 组件
  Vue.directive('drag', {
    bind(el, {value, arg, modifiers}) {
      console.log(value, arg, modifiers)
      el._value = value;
      el._isDrag = false;
      el.addEventListener('mousedown', function(e) {
 
        if (!el._value) return;
 
        el._isDrag = true;
        el._x = e.clientX - el.offsetLeft;
        el._y = e.clientY - el.offsetTop;
 
        e.preventDefault();
      });
      document.addEventListener('mousemove', function(e) {
        if (el._isDrag) {
          let l = e.clientX - el._x;
          let t = e.clientY - el._y;
 
          if (modifiers.limit) {
            if (l < 0) {
              l = 0;
            }
            if (t < 0) {
              t = 0;
            }
          }
 
          el.style.left = l + 'px';
          el.style.top = t + 'px';
        }
      });
      document.addEventListener('mouseup', function(e) {
        el._isDrag = false;
      });
    },
 
    componentUpdated(el, {value}) {
      console.log('更新了', value);
      el._value = value;
    }
  });
 
  let app = new Vue({
    el: '#app',
    data: {
      isDrag: false
    }
  });
 
 
</script>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/weixin_45895314/article/details/108696914