五、自定义指令
分类:全局指令、局部指令
1. 自定义全局指令
使用全局方法Vue.directive(指令ID,定义对象)
2. 自定义局部指令
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自定义指令</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="itany">
<!-- <h3 v-hello>{{msg}}</h3> -->
<button @click="change">更新数据</button>
<h3 v-world:wbs17022.hehe.haha="username">{{msg}}</h3>
<!-- <p v-world>南京,专业的前端培训</p> -->
<!-- <h3 v-wbs>南京</h3> -->
<input type="text" v-model="msg" v-focus>
</div>
<script>
/**
* 自定义全局指令
* 注:使用指令时必须在指名名称前加前缀v-,即v-指令名称
*/
Vue.directive('hello',{
bind(){ //常用!!
alert('指令第一次绑定到元素上时调用,只调用一次,可执行初始化操作');
},
inserted(){
alert('被绑定元素插入到DOM中时调用');
},
update(){
alert('被绑定元素所在模板更新时调用');
},
componentUpdated(){
alert('被绑定元素所在模板完成一次更新周期时调用');
},
unbind(){
alert('指令与元素解绑时调用,只调用一次');
}
});
//钩子函数的参数
Vue.directive('world',{
bind(el,binding){
// console.log(el); //指令所绑定的元素,DOM对象
// el.style.color='red';
console.log(binding); //name
}
});
//传入一个简单的函数,bind和update时调用
Vue.directive('wbs',function(){
alert('wbs17022');
});
var vm=new Vue({
el:'#itany',
data:{
msg:'welcome to itany',
username:'alice'
},
methods:{
change(){
this.msg='欢迎来到南京'
}
},
directives:{ //自定义局部指令
focus:{
//当被绑定元素插入到DOM中时获取焦点
inserted(el){
el.focus();
}
}
}
});
</script>
</body>
</html>
3. 练习
拖动页面中的元素
onmouseover onmouseout
onmousedown onmousemove onmouseup
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>练习:自定义指令</title>
<script src="js/vue.js"></script>
<style>
#itany div{
width: 100px;
height: 100px;
position:absolute;
}
#itany .hello{
background-color:red;
top:0;
left:0;
}
#itany .world{
background-color:blue;
top:0;
right:0;
}
</style>
</head>
<body>
<div id="itany">
<div class="hello" v-drag>itany</div>
<div class="world" v-drag>南京</div>
</div>
<script>
Vue.directive('drag',function(el){
el.onmousedown=function(e){
//获取鼠标点击处分别与div左边和上边的距离:鼠标位置-div位置
var disX=e.clientX-el.offsetLeft;
var disY=e.clientY-el.offsetTop;
// console.log(disX,disY);
//包含在onmousedown里面,表示点击后才移动,为防止鼠标移出div,使用document.onmousemove
document.onmousemove=function(e){
//获取移动后div的位置:鼠标位置-disX/disY
var l=e.clientX-disX;
var t=e.clientY-disY;
el.style.left=l+'px';
el.style.top=t+'px';
}
//停止移动
document.onmouseup=function(e){
document.onmousemove=null;
document.onmouseup=null;
}
}
});
var vm=new Vue({
el:'#itany',
data:{
msg:'welcome to itany',
username:'alice'
},
methods:{
change(){
this.msg='欢迎来到南京'
}
}
});
</script>
</body>
</html>