一、自定义指令基本用法
代码示例 实现自动聚焦到输入框
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>开发者工具网http://deepjava.gitee.io/go</title>
</head>
<body>
<div id="app">
<input type="text" v-focus>
<input type="text">
</div>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript">
Vue.directive('focus', {
inserted: function(el){
el.focus();
}
});
var vm = new Vue({
el: '#app',
data: {
},
methods: {
handle: function(){
}
}
});
</script>
</body>
</html>
效果: 打开页面时 鼠标自动聚焦到 使用指令的输入框上
二、带参数的自定义指令
代码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>开发者工具网http://deepjava.gitee.io/go</title>
</head>
<body>
<div id="app">
<input type="text" v-color='msg'>
</div>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript">
Vue.directive('color', {
bind: function(el, binding){
console.log(binding.value.color)
el.style.backgroundColor = binding.value.color;
}
});
var vm = new Vue({
el: '#app',
data: {
msg: {
color: 'pink'
}
},
methods: {
handle: function(){
}
}
});
</script>
</body>
</html>
三、局部指令
上面的 Vue.directive 语法格式定义的指令为全局指令
下面介绍局部指令的语法结构: 代码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>开发者工具网http://deepjava.gitee.io/go</title>
</head>
<body>
<div id="app">
<input type="text" v-color='msg'>
<input type="text" v-focus>
</div>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript">
var vm = new Vue({
el: '#app',
data: {
msg: {
color: 'cyan'
}
},
methods: {
handle: function(){
}
},
directives: {
color: {
bind: function(el, binding){
el.style.backgroundColor = binding.value.color;
}
},
focus: {
inserted: function(el) {
el.focus();
}
}
}
});
</script>
</body>
</html>
|