vue-自定义指令

自定义指令有两种定义形式

  1. 全局定义
  2. 局部定义
全局定义

Vue.directive( 指令名称, 指令的配置选项 )

//结构中使用:<input type="text" v-focus.stop = "info"> 
  // /*  v-focus  */
  Vue.directive('focus',{
    /* 每一个选项中都有四个参数 */
    bind: function () { //当指令绑定到dom元素时触发
      console.log('bind')
    },
    inserted: function ( el,b,c,d ) {// 当指令绑定的dom元素插入页面时触发
      console.log("兵哥: el", el) //这个就是指令绑定的dom
      el.focus()
      // el.style.background = 'red'
      console.log("兵哥: b", b)
      if ( b.modifiers.stop ) {
        //true 
        el.style.background = 'green'
      } else {
        //false 
        el.style.background = 'red'
      }

      el.value = b.expression
      console.log("兵哥: c  -  vNode", c)
      console.log("兵哥: d  - oldVNode", d)
    }
  })
局部定义

//结构中:<input type="text" v-my-focus>
//指令:v-my-focus
  new Vue({
    el: '#app',
    data: {
      info: '焦点'
    },
    directives: {
      // 指令名称:选项
      'my-focus': {
        inserted: function ( el ) {
          el.focus()
        }
      }
    }
  })


  new Vue({
    el: '#root'
  })
发布了55 篇原创文章 · 获赞 8 · 访问量 1790

猜你喜欢

转载自blog.csdn.net/louting249/article/details/103099002