vue 学习笔记-复用-自定义指令

全局注册和局部注册,bind/update 一起作用,对象字面量,动态指令参数

除了核心功能默认内置的指令 (v-model 和 v-show),Vue 也允许注册自定义指令

注意,在 Vue2.0 中,代码复用和抽象的主要形式是组件

然而,有的情况下,你仍然需要对普通 DOM 元素进行底层操作,这时候就会用到自定义指令。


 

全局注册

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

局部注册(组件的directives选项)

directives: {
  focus: {
    // 指令的定义
    inserted: function (el) {
      el.focus()
    }
  }
}

使用方法

<input v-focus>

指令的钩子函数:


 

 第一次:会执行bind/inserted      数值更新时候执行:update/componentUpdated 

 钩子函数参数

函数简写

bind 和 update 时触发相同行为,而不关心其它的钩子

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

对象字面量:指令函数能够接受所有合法的 JavaScript 表达式。

如果指令需要多个值,可以传入一个 JavaScript 对象字面量。

<div v-demo="{ color: 'white', text: 'hello!' }"></div>

Vue.directive('demo', function (el, binding) {
  console.log(binding.value.color) // => "white"
  console.log(binding.value.text)  // => "hello!"
})
原文地址:https://www.cnblogs.com/liuguiqian/p/11146410.html