vue自定义指令directive使用的方法是什么

其他教程   发布日期:2025年02月20日   浏览次数:191

本篇内容主要讲解“vue自定义指令directive使用的方法是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“vue自定义指令directive使用的方法是什么”吧!

1. 一个指令定义对象可以提供如下几个钩子函数(均为可选)

  • bind:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。

  • inserted:被绑定元素插入父节点时调用(仅保证父节点存在,但不一定已被插入文档中)。

  • update:只要当前元素不被移除,其他操作几乎都会触发这2个生命周期,先触发update后触发componentUpdate。虚拟DOM什么时候更新:只要涉及到元素的隐藏、显示(display)值的改变、内容的改变等都会触发虚拟DOM更新.

  • componentUpdated:组件更新

  • unbind:当使用指令的元素被卸载的时候会执行,就是当前元素被移除的时候,只调用一次

Vue.directive 内置了五个钩子函数 :

bind(绑定触发)、inserted(插入触发)、update(更新触发)、componentUpdated(组件更新触发)和unbind(解绑触发)函

  1. // 注册
  2. Vue.directive('my-directive',{
  3. bind: function () {},
  4. inserted: function () {},
  5. update: function () {},
  6. componentUpdated: function () {},
  7. unbind: function() {}
  8. })

2.指令钩子函数会被传入以下参数

  • el:指定所绑定的元素,可以用来直接操作DOM

  • binding:一个对象,包含以下属性:

    • name:指令名,不包含前缀v-

    • value:指令的绑定值,例如:v-my-directive="1+1"中,绑定值为2

    • oldValue:指令绑定的前一个值,仅在update和componentUpdated钩子中可用,无论值是否改变都可用。

    • expression: 绑定值的字符串形式。 例如 v-my-directive=“1 + 1” , expression 的值是 “1 + 1”。

    • arg: 传给指令的参数。例如 v-my-directive:foo, arg 的值是 “foo”。

    • modifiers: 一个包含修饰符的对象。 例如: v-my-directive.foo.bar, 修饰符对象 modifiers 的值是{ foo: true, bar: true }。

    • vnode: Vue 编译生成的虚拟节点

    • oldVnode: 上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用

  • vnode:vue编译生成的虚拟节点

  • oldVnode:上一个虚拟节点,仅在update和componentUpdated钩子中可用

除了el之外,其他参数都应该是只读的,不能修改。如果需要在钩子之间共享数据,建议通过元素的 dataset 来进行。

3.使用自定义指令场景的示例

drag.js

  1. import Vue from 'vue'
  2. import { Message } from 'element-ui';
  3. // 自定义指令示例1:弹窗拖拽
  4. Vue.directive('dialogDrag',{
  5. bind(el,binding,vnode,oldVnode){
  6. const dialogHeader = el.querySelector('.el-dialog__header');
  7. const dialogDom = el.querySelector('.el-dialog');
  8. dialogHeader.style.cursor = 'move'
  9. /**
  10. * 不同浏览器获取行内样式属性
  11. * ie浏览器: dom元素.currentStyle
  12. * 火狐浏览器:window.getComputedStyle(dom元素, null)
  13. */
  14. const sty = dialogDom.currentStyle || window.getComputedStyle(dialogDom, null)
  15. dialogHeader.onmousedown = (e) => {
  16. //按下鼠标,获取点击的位置 距离 弹窗的左边和上边的距离
  17. //点击的点距离左边窗口的距离 - 弹窗距离左边窗口的距离
  18. const distX = e.clientX - dialogHeader.offsetLeft;
  19. const distY = e.clientY - dialogHeader.offsetTop;
  20. //弹窗的left属性值和top属性值
  21. let styL, styT
  22. //注意在ie中,第一次获取到的值为组件自带50%,移动之后赋值为Px
  23. if(sty.left.includes('%')){
  24. styL = +document.body.clientWidth * (+sty.left.replace(/%/g,'') / 100)
  25. styT = +document,body.clientHeight * (+sty.top.replace(/%/g,'') / 100)
  26. }else{
  27. styL = +sty.left.replace(/px/g,'');
  28. styT = +sty.top.replace(/px/g,'');
  29. }
  30. document.onmousemove = function(e) {
  31. //通过事件委托,计算移动距离
  32. const l = e.clientX - distX
  33. const t = e.clientY - distY
  34. //移动当前的元素
  35. dialogDom.style.left = `${l + styL}px`
  36. dialogDom.style.top = `${t + styT}px`
  37. }
  38. document.onmouseup = function(e){
  39. document.onmousemove = null
  40. document.onmouseup = null
  41. }
  42. }
  43. }
  44. })
  45. //自定义指令示例2:v-dialogDragWidth 可拖动弹窗宽度(右侧边)
  46. Vue.directive('dragWidth',{
  47. bind(el) {
  48. const dragDom = el.querySelector('.el-dialog');
  49. const lineEl = document.createElement('div');
  50. lineEl.style = 'width: 5px; background: inherit; height: 80%; position: absolute; right: 0; top: 0; bottom: 0; margin: auto; z-index: 1; cursor: w-resize;';
  51. lineEl.addEventListener('mousedown',
  52. function (e) {
  53. // 鼠标按下,计算当前元素距离可视区的距离
  54. const disX = e.clientX - el.offsetLeft;
  55. // 当前宽度
  56. const curWidth = dragDom.offsetWidth;
  57. document.onmousemove = function (e) {
  58. e.preventDefault(); // 移动时禁用默认事件
  59. // 通过事件委托,计算移动的距离
  60. const l = e.clientX - disX;
  61. if(l > 0){
  62. dragDom.style.width = `${curWidth + l}px`;
  63. }
  64. };
  65. document.onmouseup = function (e) {
  66. document.onmousemove = null;
  67. document.onmouseup = null;
  68. };
  69. }, false);
  70. dragDom.appendChild(lineEl);
  71. }
  72. })
  73. // 自定义指令示例3:v-dialogDragWidth 可拖动弹窗高度(右下角)
  74. Vue.directive('dragHeight',{
  75. bind(el) {
  76. const dragDom = el.querySelector('.el-dialog');
  77. const lineEl = document.createElement('div');
  78. lineEl.style = 'width: 6px; background: inherit; height: 10px; position: absolute; right: 0; bottom: 0; margin: auto; z-index: 1; cursor: nwse-resize;';
  79. lineEl.addEventListener('mousedown',
  80. function(e) {
  81. // 鼠标按下,计算当前元素距离可视区的距离
  82. const disX = e.clientX - el.offsetLeft;
  83. const disY = e.clientY - el.offsetTop;
  84. // 当前宽度 高度
  85. const curWidth = dragDom.offsetWidth;
  86. const curHeight = dragDom.offsetHeight;
  87. document.onmousemove = function(e) {
  88. e.preventDefault(); // 移动时禁用默认事件
  89. // 通过事件委托,计算移动的距离
  90. const xl = e.clientX - disX;
  91. const yl = e.clientY - disY
  92. dragDom.style.width = `${curWidth + xl}px`;
  93. dragDom.style.height = `${curHeight + yl}px`;
  94. };
  95. document.onmouseup = function(e) {
  96. document.onmousemove = null;
  97. document.onmouseup = null;
  98. };
  99. }, false);
  100. dragDom.appendChild(lineEl);
  101. }
  102. })
  103. // 自定义指令示例4:图片加载前填充背景色
  104. Vue.directive('imgUrl',function(el,binding){
  105. var color=Math.floor(Math.random()*1000000);//设置随机颜色
  106. el.style.backgroundColor='#'+color;
  107. var img=new Image();
  108. img.src=binding.value;// -->binding.value指的是指令后的参数
  109. img.onload=function(){
  110. el.style.backgroundColor='';
  111. el.src=binding.value;
  112. }
  113. })
  114. // 自定义指令示例5:输入框聚焦
  115. Vue.directive("focus", {
  116. // 当被绑定的元素插入到 DOM 中时……
  117. inserted (el) {
  118. // 聚焦元素
  119. el.querySelector('input').focus()
  120. },
  121. });
  122. // 自定义指令示例6:设置防抖自定义指令
  123. Vue.directive('throttle', {
  124. bind: (el, binding) => {
  125. let setTime = binding.value; // 可设置防抖时间
  126. if (!setTime) { // 用户若不设置防抖时间,则默认2s
  127. setTime = 1000;
  128. }
  129. let cbFun;
  130. el.addEventListener('click', event => {
  131. if (!cbFun) { // 第一次执行
  132. cbFun = setTimeout(() => {
  133. cbFun = null;
  134. }, setTime);
  135. } else {
  136. /*如果多个事件监听器被附加到相同元素的相同事件类型上,当此事件触发时,
  137. 它们会按其被添加的顺序被调用。如果在其中一个事件监听器中执行 stopImmediatePropagation() ,那么剩下的事件监听器都不会被调用*/
  138. event && event.stopImmediatePropagation();
  139. }
  140. }, true);
  141. },
  142. });
  143. // 自定义指令示例7:点击按钮操作频繁给出提示
  144. Vue.directive('preventReClick', {
  145. inserted: function (el, binding) {
  146. el.addEventListener('click', () => {
  147. if (!el.disabled) {
  148. el.disabled = true
  149. Message.warning('操作频繁')
  150. setTimeout(() => {
  151. el.disabled = false
  152. //可设置时间
  153. }, binding.value || 3000)
  154. }
  155. })
  156. }
  157. })

main.js中引入文件:

  1. import '@/assets/js/drag.js'

页面使用:

  1. <template>
  2. <div>
  3. <el-button type="text" @click="dialogVisible = true">点击打开 Dialog</el-button>
  4. <div >
  5. <img v-imgUrl="url"></img>
  6. <img v-imgUrl="url"></img>
  7. <img v-imgUrl="url"></img>
  8. <img v-imgUrl="url"></img>
  9. <img v-imgUrl="url"></img>
  10. <img v-imgUrl="url"></img>
  11. <img v-imgUrl="url"></img>
  12. <img v-imgUrl="url"></img>
  13. </div>
  14. <div>
  15. <el-input placeholder="请选择日期" suffix-icon="el-icon-date" v-model="input1"></el-input>
  16. <el-input v-focus placeholder="请输入内容" prefix-icon="el-icon-search" v-model="input2"></el-input>
  17. </div>
  18. <div>
  19. <el-button type="danger" v-throttle @click="throttleBtn">危险按钮</el-button>
  20. <el-button @click="submitForm()">创建</el-button>
  21. </div>
  22. <el-dialog title="提示" v-dialogDrag v-dragWidth v-dragHeight :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
  23. <span>这是一段信息</span>
  24. <span slot="footer" class="dialog-footer">
  25. <el-button @click="dialogVisible = false">取 消</el-button>
  26. <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  27. </span>
  28. </el-dialog>
  29. </div>
  30. </template>
  31. <script>
  32. export default {
  33. data() {
  34. return {
  35. dialogVisible: false,
  36. url:'//www.baidu.com/img/flexible/logo/pc/result.png',
  37. input1: '',
  38. input2: '',
  39. }
  40. },
  41. methods: {
  42. handleClose(done) {
  43. console.log('弹窗打开')
  44. },
  45. throttleBtn(){
  46. console.log('我的用来测试防抖的按钮')
  47. },
  48. submitForm(){
  49. this.$message.error('Message 消息提示每次只能1个');
  50. }
  51. },
  52. }
  53. </script>
  54. <style>
  55. img{
  56. width: 100px;
  57. height: 100px;
  58. }
  59. </style>

以上就是vue自定义指令directive使用的方法是什么的详细内容,更多关于vue自定义指令directive使用的方法是什么的资料请关注九品源码其它相关文章!