Vue——自定义指令

全局

/**
 * 全局指令 v-ff
 * Vue.directive('ff',{})
 * 指令使用比较频繁的情况下使用全局
 * 
 * 局部指令
 * 只使用一次 或少量次数的指令 使用局部
 */
 Vue.directive('ff', {
   // 当把指令与el绑定在一起的时候触发
   bind(el, binding, vnode) {
     // 当指令绑定到元素上时触发
      // 是获取到binding的值
      el.value = binding.value
      // 绑定的值在组件中的变量名称
      const name =  binding.expression
      // 给元素添加 原生事件获取到 元素的内容变化

      //  vnode.context 你的指令所在的组件
      el.addEventListener('input', function() {
        // 通过vnode的context修改组件中对应的变量
        vnode.context[name] = el.value
      })
   },
   inserted(el, binding) {
      // 表示该指令所在的元素已经插入到dom了
      // el.focus()
   },
   update(el, binding) {
    // 当指令绑定的组件内部数据发生改变时触发该钩子函数
    el.value = binding.value
   }
 })

局部

directives: { //directives 自定义指令
focus: { // v-focus
    bind(el, binding, vnode, oldVnode) {
        // v-focus绑定到元素或组件上时触发
        // console.log('bind')
        // html 原生元素对象
        // el.focus()
        // 在这里 指令所在的元素还没有被插入到dom所以 元素一些动态操作是不能实现的
        el.style.background = 'red';
        // console.log(binding)
    },
    inserted(el, binding, vnode, oldVnode) {
        // 当指令所在的元素插入到dom时 触发这个钩子
        // console.log('inserted')
        el.focus()
    },
    update(el, binding, vnode, oldVnode) {
        // console.log('update')
    }
},

批量导入

Vue.use((Vue) => {
  ((requireContext) => {
    const arr = requireContext.keys().map(requireContext);
    (arr || []).forEach((directive) => {
      directive = directive.__esModule && directive.default ? directive.default : directive;
      Object.keys(directive).forEach((key) => {
        Vue.directive(key, directive[key]);
      });
    });
  })(require.context('../directives', false, /^\.\/.*\.js$/));
});

钩子函数的参数 (即 elbindingvnodeoldVnode),除了 el 之外,其它参数都应该是只读的,切勿进行修改。如果需要在钩子之间共享数据,建议通过元素的 dataset 来进行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值