vue中除了内置的指令(v-show,v-model)还允许我们自定义指令
想要创建自定义指令,就要注册指令(以输入框获取焦点为例) 注意:autofocus 在移动版 Safari 上不
工作
一、注册全局指令:
// 注册一个全局自定义指令 `
v-focus` Vue.directive('focus', {
// 当被绑定的元素插入到 DOM 中时……
inserted: function (el,binding) {
// 当前指令绑定的dom元素
//console.log(el);
// 指令传入的参数、修饰符、值 v-指令名称:参数.修饰符=值
// console.log(binding)
// 聚焦元素
el.focus()
}
})
二、注册局部指令: 组件中也接受一个 directives 的选项
directives: {
focus: {
// 指令的定义
inserted: function (el) {
el.focus()
}
}
}
使用也很简单:直接在元素上面使用v-focus即可:
<input type="text" v-focus/>
下面再举一个自定义指令的小例子:拖拽
Vue.directive('drag', {
// 当指令绑定到元素上的时候执行
bind(el, binding) {
// console.log('bind');
// 当前指令绑定的dom元素
//console.log(el);
// 指令传入的参数、修饰符、值 v-指令名称:参数.修饰符=值
// console.log(binding)
el.onmousedown = function(e) {
var e = e||event;
let disX = e.clientX - el.offsetLeft;
let disY = e.clientY - el.offsetTop;
document.onmousemove = function(e) {
var e = e||event;
let L = e.clientX - disX;
let T = e.clientY - disY;
if (binding.modifiers.limit) {
if (L < 0) {
L = 0;
}
}
el.style.left = L + 'px';
el.style.top = T + 'px';
};
document.onmouseup = function() {
document.onmousemove = null;
};
return false;
}
}
});
使用也很简单,只用在元素上添加v-drag或者v-drag.limit
<div id="div1" v-drag.limit></div>
<div id="div2" v-drag></div>