Vue自定义指令的运用

-Vue的指令以v-开头,除了官方的指令,有时候我们想要自己全局设定一些自定义指令,方便全局运用。

Vue.directive('name',{
   inserted:function(el){
       el.focus();           
   }
})
钩子函数
Vue.directive('name',{
   bind:function(el){
       el.style.color = "red";           
   }
})
简写模式

-在很多时候,你可能想在 bind 和 update 时触发相同行为,而不关心其它的钩子。比如这样写:

Vue.directive("fontsize",function(el,binding){
    console.log(typeof(binding.value),binding);
    el.style.fontSize = binding.value + "px";
})
自定义指令可以配合data变量,进而形成动态的样式
 <div v-fontsize='fs'>一起摇摆</div>
-在脚手架中如何引用自定义指令?

1.建一个js文件
2.在里面定义指令以及函数

import Vue from 'vue'

Vue.directive('focus',{
    inserted:function(el){
        console.log(1);
        el.focus();
    }
})
Vue.directive('title',{
    bind:function(el){
        el.style.color = "blue";
        el.classList.add("animated", "bounceInRight");
    },
    inserted:function(el){

    }
})
Vue.directive("fontsize",function(el,binding){
    console.log(typeof(binding.value),binding);
    el.style.fontSize = binding.value + "px";
})

3.在main.js引入js文件,就可以在全局使用自定义指令了。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容