这是从网上找到的一个案例,由于网上的案例有坑,所以我在这里从新上传一次!
首先在main.js里引入两个自定义指令
1 | import {focus, drag} from './components/darg.js' |
然后创建一个darg.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 | import Vue from 'vue' const focus = Vue.directive( 'focus' , { inserted: function (el) { el.focus() el.setAttribute( 'placeholder' , 'test' ) } }) const drag = Vue.directive( 'drag' ,{ inserted: function (el) { //inserted 钩子函数:当元素被插入父元素时触发,可省略 let oDiv = el; //el --> 触发的DOM元素 oDiv.style.position= 'relative' ; oDiv.onmousedown = function (e) { let l = e.clientX - oDiv.offsetLeft; let t = e.clientY - oDiv.offsetTop; document.onmousemove = function (e) { oDiv.style.left = e.clientX - l + 'px' ; oDiv.style.top = e.clientY - t + 'px' ; }; oDiv.onmouseup = function () { document.onmousemove = null ; oDiv.onmouseup = null ; } } } }) export { focus, drag} |
这里面有两个自定义指令一个是自动input自动对焦,一个是div的拖拽,红色是我遇到的坑,网上代码没有{}所以我这里标出来。
最后随意创建一个.vue的文件,这里我就创建一个Hello.vue
1 2 3 4 5 6 7 8 9 10 | <template> <div> <div class = "ddd" v-drag>我可以拖拽</div> <input type= "text" v-focus /> </div> </template> <script> </script> <style> </style> |
最后纠正下,其实顺序是先写darg.js,再引入到main.js之后就可以再Hello.vue里使用自定义指令了。、
希望对大家有帮助,谢谢
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步