第八章 自定义指令

2019-10-24  本文已影响0人  kzc爱吃梨

自定义指令的基本用法

和组件类似分全局注册和局部注册,区别就是把component换成了derective

钩子函数

代码展示
指令定义函数提供了几个钩子函数(可选):

钩子函数的参数有:

<div id="app">
  获取焦点:<input type="text" v-focus> <br>
  没获取焦点:<input type="text">
  <hr>
  <div v-cuihua:goudan.a.b.c="obq"></div>
</div>
-------------------------------------------------------------------------
<script>
Vue.directive('focus', {
  inserted: function(el){
    //指令的选项,插入到父节点四就调用
    el.focus()
  }
})

Vue.directive('cuihua', {
  bind: function(el,binding){
    el.innerHTML = 
      'name' + '---' + binding.name + '<br>' +
      'value' + '---' + binding.value + '<br>' +
      'expression' + '---' + binding.expression + '<br>' +
      'argument' + '---' + binding.arg + '<br>' +
      'modifiers' + '---' + JSON.stringify(binding.modifiers) + '<br>' 
  }
})

let app = new Vue({
  el: '#app',
  data: {
    obq: '我是指令所绑定的值'
  }
})
</script>
效果图
上一篇下一篇

猜你喜欢

热点阅读