Vue.js自定义指令及其钩子函数

对普通 DOM 元素进行底层操作,会用到自定义指令,我们以输入框获取焦点为例:

当页面加载时,输入框将获得焦

// 注册一个全局自定义指令 `v-focus`
// Vue.directive('指令名', {钩子函数} )
Vue.directive('focus', {
  // 当被绑定的元素插入到 DOM 中时……
  inserted: function (el) {
    // 聚焦元素
    el.focus()
  }
})
// 这里是Vue实例中注册一个局部指令 `v-focus`
directives: {
  focus: {
    // 指令的定义
    inserted: function (el) {
      el.focus()
    }
  }
}

在模板的所有元素中可以使用:

<input v-focus>

一个指令定义对象有常用的3个钩子函数:

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

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

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

directives: {
  // 自定义指令1
  focus1: {
    // 指令的定义
    bind: function (el) {
		el.style.color = "red"
	},
    inserted: function (el) {
      el.focus()
    },
    update: function (el) {
		el.style.color = "blue"
	}
  },
  // 自定义指令2
  focus2: {
    // 指令的定义
    bind: function (el) {
		el.style.color = "blue"
	},
    inserted: function (el) {
      el.focus()
    },
    update: function (el) {
		el.style.color = "black"
	}
  }
}

指令钩子函数会的参数:

  • el:指令所绑定的元素,可以用来直接操作 DOM。
  • binding:一个对象,包含以下 property:
    • name:指令名,不包括 v- 前缀。
    • value:指令的绑定值,例如:v-my-directive=“1 + 1” 中,绑定值为 2。
    • oldValue:指令绑定的前一个值,仅在 update 和 componentUpdated 钩子中可用。无论值是否改变都可用。
    • 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 编译生成的虚拟节点。移步 VNode API 来了解更多详情。
  • oldVnode:上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用。

举例:

<div id="example" v-demo:blue="message">div>
// 全局定义
Vue.directive('demo', {
  bind: function (el, binding, vnode) {
    var s = JSON.stringify
    el.innerHTML =
      'name: '       + s(binding.name) + '
'
+ 'value: ' + s(binding.value) + '
'
+ 'expression: ' + s(binding.expression) + '
'
+ 'argument: ' + s(binding.arg) + '
'
+ 'modifiers: ' + s(binding.modifiers) + '
'
+ 'vnode keys: ' + Object.keys(vnode).join(', ') el.style.backgroundColor = binding.value el.style.color = binding.arg } }) // 局部定义 new Vue({ el: 'example', data: { message: 'red' }, directive: { demo:{ bind: function (el, binding, vnode) { var s = JSON.stringify el.innerHTML = 'name: ' + s(binding.name) + '
'
+ 'value: ' + s(binding.value) + '
'
+ 'expression: ' + s(binding.expression) + '
'
+ 'argument: ' + s(binding.arg) + '
'
+ 'modifiers: ' + s(binding.modifiers) + '
'
+ 'vnode keys: ' + Object.keys(vnode).join(', ') el.style.backgroundColor = binding.value el.style.color = binding.arg } } } })

函数简写:

你可能想在 bind 和 update 时触发相同行为,而不关心其它钩子。可以这样写:

// bind 和 update 时触发相同行为
// Vue.directive('指令名', function函数 )
Vue.directive('color-swatch', function (el, binding) {
  el.style.backgroundColor = binding.value
})

参考Vue官方的 自定义指令

你可能感兴趣的:(前端,笔记)