vue 指令的设计实现

 

与angular 不同,vue的指令不是通过依赖注入实现的,而是通过全局的注册系统。指令通过调用 Vue 实例的 Vue.directive 方法并传入指令的名称和定义来注册。

一旦注册,该指令可以在该Vue实例或其后代渲染的任何模板中使用,只需在其名称前加上v-前缀即可。

指令定义是一个JavaScript对象,可以包含一个或多个生命周期钩子,如bind绑定、inserted插入、update更新和 unbind解除绑定。这些钩子将在指令生命周期的不同阶段被调用,允许你执行特定于该阶段的逻辑。
 
 
// my-directive.js
export default {
  bind(el, binding, vnode) {
    // 当指令第一次被绑定到元素上时,调用一次

  },
  inserted(el, binding, vnode) {
    // 当被绑定的元素被插入到其父节点时被调用 ,比如v-if  ,v-for
   
  },
  update(el, binding, vnode, oldVnode) {
    // 当组件的状态或道具发生变化时被调用,并且vdom 需要重新渲染

  },
  componentUpdated(el, binding, vnode, oldVnode) {
    // 当组件更新时被调用
  },
  unbind(el, binding, vnode) {
    // 当指令与元素解除绑定时,调用一次
  }
}


<template>
  <div>
    <input v-my-directive="message" />
  </div>
</template>

<script>
import myDirective from './my-directive.js'

export default {
  directives: {
    myDirective
  },
  data() {
    return {
      message: 'Hello World'
    }
  }
}
</script>

  

 自定义指令实现v-if

Vue.directive('if', {
  bind: function (el, binding, vnode) {
    if (binding.value) {
      el.style.display = 'none';
    }
  },
  update: function (el, binding, vnode) {
    if (binding.value) {
      el.style.display = 'none';
    } else {
      el.style.display = '';
    }
  }
});

  

 

posted @ 2021-08-06 09:02  break_happy  Views(30)  Comments(0Edit  收藏  举报