vue自定义指令的创建和使用方法实例分析

2020-06-14 05:59:48易采站长站整理

//按钮单击,count自增
this.count++;
}
},
directives:{
change:{
bind: function (el,bindings) {
console.log('指令已经绑定到元素了');
console.log(el);
console.log(bindings);
//准备将传递来的参数
// 显示在调用该指令的元素的innerHTML
el.innerHTML = bindings.value;
},
update: function (el,bindings) {
console.log('指令的数据有所变化');
console.log(el);
console.log(bindings);
el.innerHTML = bindings.value;
if(bindings.value == 5)
{
console.log(' it is a test');
}
},
unbind: function () {
console.log('解除绑定了');
}
}
}
})
</script>
</body>
</html>

使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试,可得到如下运行效果:


<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script src="https://cdn.bootcss.com/vue/2.0.1/vue.min.js"></script>
<title>www.jb51.net vue自定义指令</title>
</head>
<body>
<div id="container">
<p>{{msg}}</p>
<h1 v-change-background-color="myBgColor">
it is a header1
</h1>
</div>
<script>
new Vue({
el: '#container',
data: {
msg: 'Hello Vue',
myBgColor:'#ff0000'
},
directives:{
changeBackgroundColor:{
bind: function (el,bindings) {
console.log('in bind ');
console.log(bindings.value);
el.style.backgroundColor = bindings.value;
}
}
}
})
</script>
</body>
</html>

使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试,可得到如下运行效果:

<h4 v-change-background-color="'red'">背景色</h4>
这样也是可以的,但是写死了,不好

希望本文所述对大家vue.js程序设计有所帮助。