vue 自定义指令

本文详细介绍了Vue.js中的指令系统,包括全局和私有指令的定义及使用,以及如何抽取全局指令到单独文件。同时,展示了如何实现防抖和节流功能的自定义指令,这些指令可以用于优化UI更新和事件处理,提高应用性能。
摘要由CSDN通过智能技术生成

自定义指令

1、定义全局指令

Vue.directive('focus', {
  // 当被绑定的元素插入到 DOM 中时……
  inserted: function (el) {
    el.focus()
  }
})

2、定义私有指令

directives: {
  focus: {
    inserted: function (el) {
      el.focus()
    }
  }
}

使用:

<input v-focus>

函数简写

在很多时候,你可能想在 bindupdate 时触发相同行为,而不关心其它的钩子。比如这样写:

Vue.directive('color-swatch', function (el, binding) {
  el.style.backgroundColor = binding.value
})

指令的钩子函数

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

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

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

  • update:所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变,也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新

  • componentUpdated:指令所在组件的 VNode 及其子 VNode 全部更新后调用。

  • unbind:只调用一次,指令与元素解绑时调用。

钩子函数的参数

所有的指令钩子函数都会被传入一下参数:

  • el:指令所绑定的元素,可以用来直接操作 DOM。
  • binding:一个对象,包含以下 property:
    • name:指令名。
    • value:指令的绑定值,例如:v-my-directive=“1 + 1” 中,绑定值为 2。
    • oldValue:指令绑定的前一个值,仅在 updatecomponentUpdated 钩子中可用。
    • expression:字符串形式的指令表达式。例如 v-my-directive=“1 + 1” 中,表达式为 “1 + 1”。
    • arg:传给指令的参数,可选。例如 v-my-directive:foo 中,参数为 “foo”。
    • modifiers:一个包含修饰符的对象。例如:v-my-directive.foo.bar 中,修饰符对象为 { foo: true, bar: true }。
  • vnode:Vue 编译生成的虚拟节点。
  • oldVnode:上一个虚拟节点,仅在 updatecomponentUpdated 钩子中可用。

看下例:

<div id="hook-arguments-example" v-demo:foo.a.b="message"></div>
Vue.directive('demo', {
  bind: function (el, binding, vnode) {
    var s = JSON.stringify
    el.innerHTML =
      'binding.name: '       + s(binding.name) + '<br>' +
      'binding.value: '      + s(binding.value) + '<br>' +
      'binding.expression: ' + s(binding.expression) + '<br>' +
      'binding.arg: '   + s(binding.arg) + '<br>' +
      'binding.modifiers: '  + s(binding.modifiers) + '<br>'
  }
})

new Vue({
  el: '#hook-arguments-example',
  data: {
    message: 'hello!'
  }
})
# 结果
binding.name: "demo"
binding.value: "hello!"
binding.expression: "message"
binding.arg: "foo"
binding.modifiers: {"a":true,"b":true}

抽取全局指令

1、将全局指令单独放在一个文件 directives.js

// 1、对象写法
export const test = {
  inserted: function (el, binding, vnode, oldVnode) {
    console.log(el, binding, vnode, oldVnode)
  },

  bind: function(el, binding, vnode, oldVnode) {
    el.style.color = 'red'
  },

  update: function (el, binding, vnode, oldVnode) {
    console.log(el, binding, vnode, oldVnode)
  }
}
// 2、函数简写
export const focus = (el, binding, vnode, oldVnode) => {
  console.log('focus', el)
  el.focus()
}

2、在 main.js 中注册:

import * as directives from './directives/index'
Object.keys(directives).forEach(key => {
  Vue.directive(key, directives[key])
})

防抖与节流指令

/**
 * 防抖
 * eg: <view v-debounce:click.wait.stop="getData">查询</view>
 */
export const debounce = {
  bind: function (el, binding) {
    let timer = null; // 定时器
    let implement = true;  //
    if (binding.value && binding.arg) {
      el.addEventListener(binding.arg, (e) => {
        // 阻止事件冒泡修饰符
        if (binding.modifiers && binding.modifiers.stop) {
          e.stopPropagation();
        }
        timer && clearTimeout(timer);
        if(binding.modifiers && binding.modifiers.wait) { // 1. 先等待后执行
          timer = setTimeout(() => {
            binding.value();
          }, 650);
        } else {  // 2. 先执行后等待
          implement && binding.value();
          implement = false;
          timer = setTimeout(() => {
            implement = true;
          }, 650);
        }
      })
    }
  }

};


/**
 * 节流
 * eg: <input v-throttle:input.wait="getData" />
 */
export const throttle = {
  bind: function (el, binding) {
    let timer = null;
    let implement = true;
    if (binding.value && binding.arg) {
      el.addEventListener(binding.arg, (e) => {
        // 阻止事件冒泡修饰符
        if (binding.modifiers && binding.modifiers.stop) {
          e.stopPropagation();
        }
        if (binding.modifiers && binding.modifiers.wait) {  // 1. 先等待后执行
          if(!timer) {
            timer = setTimeout(() => {
              binding.value();
              clearTimeout(timer);  // 内存回收
              timer = null;
            }, 650);
          }
        } else {  // 2. 先执行后等待
          implement && binding.value();
          implement = false;
          if(!timer) {
            timer = setTimeout(() => {
              implement = true;
              clearTimeout(timer);  // 内存回收
              timer = null;
            }, 650);
          }
        }
      })
    }
  }

};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值