自定义指令

自定义指令

  • 全局自定义指令
  • 局部自定义指令
    • 指令的钩子函数(一共有5个)
      • bind : 指令和元素第一次绑定的时候调用
      • inserted : 指令绑定的元素插入父节点的时候调用
      • update : 指令绑定的元素自身, 或是他的内容(子节点)发生改变的时候出发
      • componentUpdated : 指令绑定的组件自身, 或是他的内容(子节点)发生改变的时候出发
      • unbind : 指令和元素第一次解绑是调用
  • 指令的钩子函数的参数
    • el 当前元素
    • binding 当前指令的所有信息
    • vNode 当前指令绑定的虚拟节点
    • oldVnode 指令绑定前的虚拟节点

directive-全局

<body>
          <div id="app">
            <div v-append v-if = "flag">
                {{ msg }}
            </div>
            <input type="text" v-focus>
        </div>
</body>
<script>
/*
业务:
当我打开页面的时候, input框自动获得焦点?
*/
// Vue.directive(指令的名称,指令的配置项(钩子函数))
Vue.directive('focus',{
/* 钩子函数 */
      bind () {
           console.log('指令和元素第一次绑定')
     },
     inserted ( el, binding, vnode, oldVnode ) {
            console.log('el',el)
            console.log('binding',binding)
            console.log('vnode',vnode)
            console.log('oldvnode',oldVnode)
            el.focus()
            el.style.background = 'red'
              }
    })
Vue.directive('append',{
          inserted (el) {
                var p = document.createElement('P')
                p.innerHTML = '你好吗'
                el.appendChild(p)
            },
        update () {
              console.log('update')
          },
       componentUpdated () {
               console.log( 'componentUpdated' )
          },
       unbind ( el ) {
               console.log( 'unbind' )
          }
    })
new Vue({
        el: '#app',
       data: {
      msg: 'hello 指令',
      flag: true
      }
})
</script>

directive-局部

<body>
      <div id="app">
            <input type="text" v-focus.yyb = 'yyb'>
      </div>
</body>
<script>
/*
推理:
v-for = 'item in list'
*/
new Vue({
      el: '#app',
       data: {
             yyb: '复仇者联盟4上线',
              item: 10
          },
      directives: {
              'focus': {
              inserted ( el,binding ) {
              console.log( 'binding' , binding)
       if( binding.modifiers.junge ){
            el.style.background = 'red'
       }else{
             el.style.background = 'yellow'
        }
     el.focus()
   }
}
}
})
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值