vue教程2-07 自定义指令

时间:2023-11-22 13:25:20

vue教程2-07 自定义指令

自定义指令:
一、属性: Vue.directive(指令名称,function(参数){
this.el -> 原生DOM元素
}); <div v-red="参数"></div> 指令名称: v-red -> red * 注意: 必须以 v-开头 拖拽:
-------------------------------
  二、自定义元素指令:(用处不大)
Vue.elementDirective('zns-red',{
bind:function(){
this.el.style.background='red';
}
});

自定义指令写法一:

<div id="box">
<span v-red>
asdfasd
</span>
</div> Vue.directive('red',function(){
this.el.style.background='red';
}); window.onload=function(){
var vm=new Vue({
el:'#box',
data:{
msg:'welcome'
}
});
};

自定义指令写法二:推荐写法

<div id="box">
<span v-red="a">
asdfasd
</span>
</div>
//这里的color可以传参
Vue.directive('red',function(color){
this.el.style.background=color;
}); window.onload=function(){
var vm=new Vue({
el:'#box',
data:{
a:'blue'
}
});
};

自定义指令写法三:

<div id="box">
<span v-red>
asdfasd
</span>
</div> Vue.directive('red',{
bind:function(){
this.el.style.background='red';
}
}); window.onload=function(){
var vm=new Vue({
el:'#box'
});
};

自定义指令:拖拽drag

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="vue.js"></script>
<script>
Vue.directive('drag',function(){
var oDiv=this.el;
oDiv.onmousedown=function(ev){
var disX=ev.clientX-oDiv.offsetLeft;
var disY=ev.clientY-oDiv.offsetTop; document.onmousemove=function(ev){
var l=ev.clientX-disX;
var t=ev.clientY-disY;
oDiv.style.left=l+'px';
oDiv.style.top=t+'px';
};
document.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
};
};
}); window.onload=function(){
var vm=new Vue({
el:'#box',
data:{
msg:'welcome'
}
});
}; </script>
</head>
<body>
<div id="box">
<div v-drag :style="{width:'100px', height:'100px', background:'blue', position:'absolute', right:0, top:0}"></div>
<div v-drag :style="{width:'100px', height:'100px', background:'red', position:'absolute', left:0, top:0}"></div>
</div> </body>
</html>

自定义元素指令

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
zns-red{
width:100px;
background: gray;
height:100px;
display: block;
}
</style>
<script src="vue.js"></script>
<script>
Vue.elementDirective('zns-red',{
bind:function(){
this.el.style.background='red';
}
}); window.onload=function(){
var vm=new Vue({
el:'#box',
data:{
a:'blue'
}
});
}; </script>
</head>
<body>
<div id="box">
<zns-red></zns-red>
</div> </body>
</html>