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相关文章推荐
- vue笔记之自定义指令
- vue学习笔记6 Vue.directive自定义指令
- vue学习笔记:3.自定义指令
- Vue 2.0学习笔记:自定义指令
- 前端笔记之Vue(三)生命周期&CSS预处理&全局组件&自定义指令
- VUE学习笔记——AJAX
- Vue.directive 自定义指令的问题小结
- VUE自定义指令钩子函数讲解
- 20190215-vue学习笔记2
- vue学习笔记2——指令v-text && v-html && v-bind
- vue学习笔记(六)【class类样式、style样式】
- Vue学习笔记1.0(第二天)
- Vue.js学习笔记: 插值
- VUE学习笔记——利用es6模板字符串实现时间格式化
- vue笔记一
- Vue.js 2.0之全家桶系列视频课程——笔记(三)
- vue笔记(二)
- vue通过axios与后端交互(笔记)
- Vue学习3-7.生命周期;8.自定义指令;9.过滤器;10.路由
- 前端笔记之Vue(一)初识SPA和Vue&webpack配置和vue安装&指令