您的位置:首页 > Web前端 > Vue.js

vue自定义指令笔记

2019-07-24 21:12 78 查看
原文链接:http://www.cnblogs.com/zhaobao1830/p/11240887.html

https://cn.vuejs.org/v2/guide/custom-directive.html

在vue中,有时候我们会把抽象的方法封装为一个自定义指令,多个地方共用

比如:拖拽指令

1 <div id="myChart1" class="myChart1" v-drag>
2       {{positionX}}
3       {{positionY}}
4 </div>
1 data () {
2       return {
3         positionX: 0,
4         positionY: 0,
5         parentWidth: 0,
6         parentHeight: 0
7       }
8     },
9     directives: {
10       drag: {
11         inserted: function (el, binding, vnode) {
12           let _this = vnode.context // 指令里要想获取vue实例,可以使用vnode.context
13           let parentWidth = _this.$refs.test.offsetWidth
14           let parentHeight = _this.$refs.test.offsetHeight
15           let odiv = el // 获取目标元素
16           odiv.onmousedown = (e) => {
17             console.log(e) // 这俩个e一样
18             // 算出鼠标相对元素的位置
19             let disX = e.clientX - odiv.offsetLeft
20             let disY = e.clientY - odiv.offsetTop
21
22             // 并移动的事件
23             document.onmousemove = (e) => {
24               console.log(e) // 这俩个e一样
25               // 用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
26               let left = 0
27               let top = 0
28               if ((e.clientX - disX) < 0) {
29                 left = 0
30               } else if ((e.clientX - disX) > (parentWidth - odiv.offsetWidth)) {
31                 left = parentWidth - odiv.offsetWidth
32               } else {
33                 left = e.clientX - disX
34               }
35
36               if ((e.clientY - disY) < 0) {
37                 top = 0
38               } else if ((e.clientY - disY) > (parentHeight - odiv.offsetHeight)) {
39                 top = parentHeight - odiv.offsetHeight
40               } else {
41                 top = e.clientY - disY
42               }
43
44               // 绑定元素位置到positionX和positionY上面
45               _this.positionX = top
46               _this.positionY = left
47
48               // 移动当前元素
49               odiv.style.left = left + 'px'
50               odiv.style.top = top + 'px'
51             }
52             document.onmouseup = (e) => {
53               document.onmousemove = null
54               document.onmouseup = null
55             }
56           }
57         }
58       }
59     },

 

备注:

   1、使用this.$refs获取动态值的时候,要这样写   this.$refs['value']

   2、拖拽的div样式要特别注意:position要为absolute,不能用transform: translate(),否则拖拽后样式会异常

             

 

转载于:https://www.cnblogs.com/zhaobao1830/p/11240887.html

3ff7
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: