美文网首页Vue学习笔记
Vue自定义指令(directive)笔记

Vue自定义指令(directive)笔记

作者: 梦之卿知 | 来源:发表于2017-05-18 15:11 被阅读644次

Vue.directive (自定义指令)

使用方法,类似v-model等内置指令,2.0的为了提升性能,所以在指令中不能插入filter。

定义指令
//全局注册
/**
*   @param name:指令名称(使用时是v-name)
*   @param options:钩子函数,在不同阶段触发
**/
Vue.directive('minLength',{
  bind: function (el,binding) {
  },
  inserted: function (el,binding) {
  },
  update: function (el, binding, vnode, oldVnode) {
    });
  },
  componentUpdated: function () {},
  unbind: function () {}
});
/*简单模式*/
Vue.directive('minLength',function(){
  /*在bind和update阶段触发*/
})
//局部注册
new Vue({
  directives:{
    'name':{
      
    }
  }
})
钩子函数详解
  1. bind
  1. 触发时机:指令绑定到元素时执行一次,用于执行一些初始化动作

  2. 参数:

    • el: 绑定的DOM节点

      <input data-v-905d7216="" id="show" readonly="readonly">
      
    • binding: 绑定信息

      {
      
       arg:"arg",                              //绑定的参数,v-name:arg
    name:"name",          //指令名称
    rawName:'v-name',     //绑定到DOM时名称
     value:'value',           //绑定数据的值,默认为0
     expression:'data-key',   //绑定数据的key值
     def:Object,              //钩子函数,bind等
     modifiers:Object     //包含修饰符的对象,例如:
                       v-name.modify,modifiers对象是{modify:true}
 }
 ```
  • VNode:当前DOM节点与组件的全面信息

  • oldVNode:旧虚拟节点信息(bind时无)

  1. inserted

    1. 触发时机:被绑定的元素插入父节点时调用(父节点存在即可)
    2. 参数:同bind
  2. update

    1. 触发时机: 被绑定元素所在模块更新时调用,不是根据绑定值的变化
    2. 参数与bind对比:
      • binding参数多一个字段:oldValue,记录模块更新前的值
      • oldVNode参数值为旧虚拟节点信息
  3. componentUpdated

    1. 触发时机: 被绑定元素所在模块完成一次更新周期后触发
    2. 参数同update
  4. unbind

    1. 触发时机:指令从元素解绑时调用(一次)
    2. 解绑方式,虚拟dom销毁时自动解绑(切换组件或则手动调用vm.$destroy()方法)
    3. 参数同update
简单示例(模拟v-model指令)
/*定义指令*/
Vue.directive('my-model',{
  bind: function (el,binding,vNode,oldVNode) {
    el.value=binding.value;
  },
  inserted: function (el,binding,vNode,oldVNode) {
    el.addEventListener('keyup',function (event) {
      if(vNode.context[binding.expression]!==el.value+event){
        vNode.context[binding.expression]=el.value
      }
    })
  },
  update: function (el,binding,vNode,oldVNode) {
    if(el.value !==binding.value){
      el.value=binding.value
    }
  },
  componentUpdated: function (el,binding,vNode,oldVNode) {

  },
  unbind: function (el,binding,vNode,oldVNode) {

  }
});

组件中使用自定义指令

<template>
  <div class="directive">
    <label for="test">输入</label><input id="test" v-model="msg"/>
    <label for="show">显示</label><input id="show" v-my-model="msg"><br>
  </div>
</template>

<script>
  export default {
    name: 'directive',
    data () {
      return {
        msg: 'directive'
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .directive{

  }
</style>
相关链接

相关文章

网友评论

    本文标题:Vue自定义指令(directive)笔记

    本文链接:https://www.haomeiwen.com/subject/fllsxxtx.html