03.自定义指令

使用Vue的静态方法directive,我们可以定义属于自己的指令。

语法 :Vue.directive(指令的名字, 回调函数)

例子

<template>
  <div>
    <input type="text" v-red>
  </div>
</template>
<script>
import Vue from 'vue';
Vue.directive('red', (el)=>{
    el.style.color = 'red';
});
export default {
}
</script>

标签使用了v-red指令后,字体颜色会变红。回调函数里的el就是被绑定的v-red的input。 需要注意的是,directive函数里的指令名字不要带 “v-" 

 

指令传参

指令后面加上 = “”可以以字符串的形式传参。(而且也只能以字符串的形式传递参数) 

如 :

v-set="{size:'40px', color:'blue'}"

例子 :

<template>
  <div>
    <span v-set='{size : "40px", color : "blue"}'>hello</span>
  </div>
</template>
<script>
import Vue from 'vue';
Vue.directive('set', (el,binding)=>{
  el.style.fontSize = binding.value.size;
  el.style.color = binding.value.color;
});
export default {
}
</script>

其它自定义指令例子

自定义拖拽指令

<template>
  <div class='box' v-drag></div>
</template>
<script>
export default {
  directives : {
    drag(el){
      el.onmousedown = function(e){
        let elX = e.clientX - el.offsetLeft;
        let elY = e.clientY - el.offsetTop;
        document.onmousemove = function(e){
          var l = e.clientX - elX;
          var t = e.clientY - elY;
          el.style.left = l + 'px';
          el.style.top = t + 'px';
        }
        document.onmouseup = function(){
          document.onmousedown = document.onmousemove = null;
        }
      }
    }
  }
}
</script>
<style>
  .box{
    width: 200px;
    height: 200px;
    background: red;
    position: absolute;
    top: 0;
    left: 0;
  }
</style>

input自动获得焦点指令

<template>
  <input type="text" v-focus>
</template>
<script>
export default {
  directives : {
     focus: {
      inserted: function (el) {
        el.focus()
      }
    }
  }
}
</script>

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值