Vue.directive注册(全局与局部)自定义指令使用详解与实战

指令定义函数提供了几个钩子函数(可选):

  • bind: 只调用一次,指令第一次绑定到元素时调用,可以定义一个在绑定时执行一次的初始化动作。
  • inserted: 被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于 document 中)。
  • update: 被绑定元素所在的模板更新时调用,而不论绑定值是否变化。通过比较更新前后的绑定值。
  • componentUpdated: 被绑定元素所在模板完成一次更新周期时调用。
  • unbind: 只调用一次, 指令与元素解绑时调用。
// 注册一个全局自定义指令
Vue.directive('custom-directive', {
  bind(el, binding, vnode) {
    // bind钩子函数,在指令第一次绑定到元素时调用
    // 可以执行一次性的初始化操作
    console.log('Directive bound!');
  },
  inserted(el, binding, vnode) {
    // inserted钩子函数,在绑定元素插入父节点时调用
    console.log('Element inserted into parent node!');
  },
  update(el, binding, vnode, oldVnode) {
    // update钩子函数,在绑定元素所在的模板更新时调用
    // 可以通过比较更新前后的绑定值进行一些操作
    console.log('Directive updated!');
  },
  componentUpdated(el, binding, vnode, oldVnode) {
    // componentUpdated钩子函数,在绑定元素所在模板完成一次更新周期时调用
    console.log('Directive component updated!');
  },
  unbind(el, binding, vnode) {
    // unbind钩子函数,在指令与元素解绑时调用
    console.log('Directive unbound!');
  }
});

Vue 允许注册自定义指令。它的作用价值在于当开发人员在某些场景下需要对普通 DOM 元素进行操作。
Vue自定义指令有全局注册和局部注册两种方式。

注册全局指令的方式

// 注册一个全局自定义指令
Vue.directive('custom-directive', {
  bind(el, binding, vnode) {
    // 指令与元素绑定时调用
    el.style.color = binding.value;
  },
  update(el, binding, vnode) {
    // 指令所在元素更新时调用,可以处理新值和旧值的变化
    el.style.color = binding.value;
  }
});
 <!-- 全局注册指令 -->
<p v-custom-directive="'red'">Global Directive Example</p>

v-draggable实例
需求:实现一个拖拽指令,可在页面可视区域任意拖拽元素。
思路:

  1. 设置需要拖拽的元素为相对定位,其父元素为绝对定位。
  2. 鼠标按下(onmousedown)时记录目标元素当前的 left 和 top 值。
  3. 鼠标移动(onmousemove)时计算每次移动的横向距离和纵向距离的变化值,并改变元素的 left 和 top 值
  4. 鼠标松开(onmouseup)时完成一次拖拽
  •  inserted: 被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于 document 中)。
const draggable = {
  inserted: function (el) {
    el.style.cursor = 'move'
    el.onmousedown = function (e) {
      let disx = e.pageX - el.offsetLeft
      let disy = e.pageY - el.offsetTop
      document.onmousemove = function (e) {
        let x = e.pageX - disx
        let y = e.pageY - disy
        let maxX = document.body.clientWidth - parseInt(window.getComputedStyle(el).width)
        let maxY = document.body.clientHeight - parseInt(window.getComputedStyle(el).height)
        if (x < 0) {
          x = 0
        } else if (x > maxX) {
          x = maxX
        }
 
        if (y < 0) {
          y = 0
        } else if (y > maxY) {
          y = maxY
        }
 
        el.style.left = x + 'px'
        el.style.top = y + 'px'
      }
      document.onmouseup = function () {
        document.onmousemove = document.onmouseup = null
      }
    }
  },
}
export default draggable

批量注册指令,新建 directives/index.js 文件

import draggable from './draggable'
import longpress from './longpress'
// 自定义指令
const directives = {
  draggable,
  longpress,
}
 
export default {
  install(Vue) {
    Object.keys(directives).forEach((key) => {
      Vue.directive(key, directives[key])
    })
  },
}

import draggable from './draggable' 和 import longpress from './longpress':这两行代码是在当前文件中导入了名为 draggable 和 longpress 的自定义指令。

const directives = { draggable, longpress }:这里创建了一个对象 directives,包含了两个属性 draggable 和 longpress,分别对应上面导入的两个自定义指令。

export default { ... }:这是一个 ES6 的模块导出语法,导出了一个对象。这个对象具有一个名为 install 的方法,这个方法用于注册 Vue.js 自定义指令。

Object.keys(directives).forEach((key) => { Vue.directive(key, directives[key]) }):在 install 方法中,使用 Object.keys(directives) 获取 directives 对象的所有键名(即 draggable 和 longpress),然后通过 forEach 循环遍历这些键名。在循环的每一步中,使用 Vue.directive(key, directives[key]) 将相应的自定义指令注册到 Vue.js 中,使得这些指令可以在 Vue 组件中使用。

在 main.js 引入并调用

import Vue from 'vue'
import Directives from './JS/directives'
Vue.use(Directives)

使用: 在 Dom 上加上 v-draggable 即可

<template>
  <div class="el-dialog" v-draggable></div>
</template>

布局自定义指令:注册了布局自定义指令后,可以在 Vue 模板中使用该指令

<template>
  <div>
    <!-- 局部注册指令 -->
    <p v-custom-directive="'blue'">Local Directive Example</p>
  </div>
</template>

<script>
// 引入Vue.js并定义组件
import Vue from 'vue';

export default {
  directives: {
    'custom-directive': {
      bind(el, binding, vnode) {
        // 指令与元素绑定时调用
        el.style.color = binding.value;
      },
      update(el, binding, vnode) {
        // 指令所在元素更新时调用,可以处理新值和旧值的变化
        el.style.color = binding.value;
      }
    }
  }
};
</script>

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码海扬帆:前端探索之旅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值