Vue 每日记录一点点

2020-08-12  本文已影响0人  柒月_学前端

自定义指令 directive

// 注册一个全局自定义指令
Vue.directive('boxStyle', {
  // 当被绑定的元素插入到 DOM 中时……
  inserted: function (el) {
    // 改变该元素的背景颜色
    el.style.background = 'skyblue'
  }
})
  • 可作用于任何DOM元素上
// 注册局部自定义指令
directives: {
      focus: {
        // 指令的定义
        inserted: function (el) {
          el.style.background = 'yellow'
        }
      }
    },

用法都是相同的

<!-- 用法:v-xxx 定义的名字 -->
<ul v-focus>
      <li v-for="item of arr" :key="item">{{item}}</li>
</ul>
  • 自定义指令可设置参数
Vue.directive('pin', {
  bind: function (el, binding) {
    //el: 要操作的节点元素
    // binding:传递的参数
    el.style.position = 'fixed'
    el.style.top = binding.value + 'px'
    console.log(binding, 'node')
  }
})
// 用指令时 v-pin="200" 200就是 binding.value
<a-button v-pin="200" @click="handlecilck">检查是否为变位词</a-button>

动态参数

Vue.directive('pin', {
  bind: function (el, binding) {
    el.style.position = 'fixed'
    const s = (binding.arg == 'left' ? 'left' : 'top')
    el.style[s] = binding.value + 'px'
    console.log(binding, 'binding')
  }
})
// 用法
<a-button v-pin:[dir]="200" @click="handlecilck">检查是否为变位词</a-button>


data () {
  return {
    dir: 'top'
  }
}
上一篇 下一篇

猜你喜欢

热点阅读