天天看点

Vue API(directives) 自定义指令

前言:除了vue的内置指令以外,我们可以定义自定义指令。内置指令表相见:

我们定义一个最简单的

<script>
export default {
  name: 'App',
  data(){
    return{
      yanse:'red'
    }
  },
  // 所有自定义指令
  directives:{
    zzh(el,binding){
      console.log(el);
      console.log(binding);
      el.style='color:'+binding.value;
    }
  }
}
</script>      

 我们在这里定义了一个指令,用于改变字体的颜色,我们如何去调用我们自定义的指令,实际上你就可以当作是内置指令一样去调用它了!

Vue API(directives) 自定义指令

给zzh绑定的值一定要是 具体的数据/state/computed,不可以直接绑定值。

其中el是绑定的这个dom,而binding里是一些源数据

Vue API(directives) 自定义指令

 其中呢,我们不光可以去指定它的style,能干的事情还有很多,我们再去指定一下它的className,为了演示效果,我们引用一下animate.css,在main.js全局注册一下就好.

fadeInDown(el){
      el.className = 'animated fadeInDown';
 }      

 在dom标签上写上classname就ok了。