Vue自定义指令

109 阅读2分钟

Vue自定义指令

1.自定义指令函数式

函数方式自定义指令就是把指令写成一个函数,不需要配置钩子函数

函数回调参数如下:

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

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

    • name:指令名,不包括 v- 前缀。
    • 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 编译生成的虚拟节点。移步 VNode API 来了解更多详情。

  • oldVnode:上一个虚拟节点,仅在 updatecomponentUpdated 钩子中可用。

需求:自定义一个v-big指令,将绑定的数据乘10

 <div>
     <h3>原始数据number:{{ number }}</h3>
     绑定数据并放大十倍:<input type="text" v-big="number" />
     <button @click="number += 1">点击原始数据+1</button>
 </div>

自定义指令:

 directives: {
     big(element, binding) {
         element.value = binding.value * 10;
     },
 }

2.自定义指令对象式

回调函数:

  • bind: 只调用一次,指令第一次绑定到元素时调用。
  • inserted:被绑定元素插入父节点时调用。
  • update:Vue实例对象中data中定义任何数据发生变化是都会被调用。

需求:定义一个v-fbind 指令不仅可以绑定数据并且给input输入框自动聚焦

 <div>
     <h3>原始数据number:{{ number }}</h3>
     绑定数据并放大十倍:<input type="text" v-big="number" />
     <button @click="number += 1">点击原始数据+1</button>
     <br/><br/>
     绑定数据并聚焦:<input v-fbind="number"></input>
 </div>

v-fbind指令:

 directives: {  
     fbind: {
         inserted(element, binding) {
             element.focus();
         },
         bind(element, binding) {
             element.value = binding.value;
         },
         update(element, binding) {
             element.value = binding.value;
         },
     },
 },

3.全局指令注册

第一种方式:

 Vue.directive('pin', {
   bind: function (el, binding, vnode) {
     el.style.position = 'fixed'
     el.style.top = binding.value + 'px'
   }
 });

第二种方式:

 import hasRole from './permission/hasRole'
 import hasPermi from './permission/hasPermi'
 import dialogDrag from './dialog/drag'
 import dialogDragWidth from './dialog/dragWidth'
 import dialogDragHeight from './dialog/dragHeight'
 import clipboard from './module/clipboard'
 ​
 const install = function(Vue) {
   Vue.directive('hasRole', hasRole)
   Vue.directive('hasPermi', hasPermi)
   Vue.directive('clipboard', clipboard)
   Vue.directive('dialogDrag', dialogDrag)
   Vue.directive('dialogDragWidth', dialogDragWidth)
   Vue.directive('dialogDragHeight', dialogDragHeight)
 }
 ​
 if (window.Vue) {
   window['hasRole'] = hasRole
   window['hasPermi'] = hasPermi
   Vue.use(install); // eslint-disable-line
 }
 ​
 export default install

4.常用的内置指令

  • v-ifv-else
  • v-show
  • v-textv-html
  • v-for
  • v-onv-bind
  • v-oncev-cloak

注意: 1.指令定义时不加v-,但使用时要加v-; 2.指令名如果是多个单词,要使用kebab-case命名方式,不要用camelCase命名。

5.常见的Dom方法

el.parentNode && el.parentNode.removeChild(el); //删除子节点