vue2 自定义指令

自定义局部指令

directives这个配置项内,可以定义多个自定义指令,与data同级

定义指令注意的点:

  • v- 不需要写
  • Vue官方建议,指令名都小写,如果是多个单词,用‘-’连接
  • 语法:指令名:回调函数

回调函数接受参数:

  1. el:指令所绑定的元素,可以用来直接操作 DOM
  2. binding:一个对象,包含和自定义的指令有关的信息
    • name:指令名,不包括 v- 前缀
    • value:指令的绑定值,例如:v-my-directive="1 + 1" 中,绑定值为 2
  3. …更多可参考vue2官网 vue2自定义指令

回调函数执行时机:

  1. 执行时机1:标签和指定第一次绑定的时候
  2. 执行时机2:当模版被重新解析的时候

写法一 :函数式写法

 let vm = new Vue({
    el: '#root',
    data(){
      return {
      }},
     directives: {
     // 写法一 :函数式写法    
     // 指令名:回调函数
      "text-danger": function (element, binding) {
         // 与属性绑定,且将文字颜色替换为红色
        element.innerText = binding.value;
        element.style.color = "red";
          },
     }
   })

写法二、 对象式

 let vm = new Vue({
    el: '#root',
    data(){
      return {
      }},
     directives: {
     // 写法二、 对象式
     // 指令名:{}
      "bind-blue": {
            // 对象中有3个固定写法的函数,这三个函数在不同的时机会被调用
            // 像这种在特定的时间节点调用特定的函数,这种函数叫钩子函数

            // bind() 元素与指令初次绑定时执行
            bind(element, binding) {
              element.value = binding.value;
            },
            // inserted()  元素被插入页面之后执行
            inserted(element, binding) {
              element.parentNode.style.backgroundColor = "green";
            },
            //update() 当模版重新解析的时候,会被执行
            update(element, binding) {
            element.value = binding.value;
            },
          },
     }
   })

自定义全局指令

只是配置项的写法不一样,为全局配置写法,写在Vue实例上面,其它和局部自定义属性一样

语法:

Vue.directive(
)

函数写法:

  // 函数式 Vue.directive('指令名',回调函数)
      Vue.directive('text-danger',function(element,binging){
          element.innerText=binging.value
          element.style.color='red'
      })

对象写法:

 // 对象式 Vue.directive('指令名',{bind(){},inserted(){},update(){}})
      Vue.directive('bind-blue',{
        bind(element,binging){
          element.value=binging.value
        },
        inserted(element,binging){
          element.parentNode.style.backgroundColor='blue'
        },
        update(element,binging){
          element.value=binging.value
        }
      })
  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十七同志

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值