使用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>