1. 自定义指令
1.1. 代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>自定义指令</title>
</head>
<body>
<div id="app">
<div>用户名: <input type="text" v-model="userName" /></div>
<div>密码: <input type="password" v-focus v-model="password" /></div>
</div>
<script type="text/javascript" src="vue.min.js"></script>
<script type="text/javascript">
// 自定义指令
Vue.directive("focus", {
// inserted被绑定元素插入父节点时调用
inserted: function(el){
// el表示指令所绑定的元素
el.focus();
}
});
var vm = new Vue({
el: "#app",
data: {
userName: "张三",
password: "123456"
}
});
</script>
</body>
</html>
1.2. 效果图
2. 自定义指令传递参数
2.1. 代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>自定义指令传递参数</title>
</head>
<body>
<div id="app">
<div>用户名: <input type="text" v-model="userName" v-color="msg" /></div>
<div>密码: <input type="password" v-model="password" /></div>
</div>
<script type="text/javascript" src="vue.min.js"></script>
<script type="text/javascript">
// 自定义指令
Vue.directive("color", {
inserted: function(el, binding){
// el表示指令所绑定的元素
console.log(binding);
el.style.backgroundColor = binding.value.color;
}
});
var vm = new Vue({
el: "#app",
data: {
userName: "张三",
password: "123456",
msg: {id: 1001, color: "green"}
}
});
</script>
</body>
</html>
2.2. 效果图
3. 局部自定义指令
3.1. 代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>局部自定义指令</title>
</head>
<body>
<div id="app">
<div>用户名: <input type="text" v-model="userName" v-color="msg" /></div>
<div>密码: <input type="password" v-model="password" v-focus /></div>
</div>
<script type="text/javascript" src="vue.min.js"></script>
<script type="text/javascript">
var vm = new Vue({
el: "#app",
data: {
userName: "张三",
password: "123456",
msg: {id: 1001, color: "green"}
},
methods: {
},
directives: {
focus: {
inserted: function(el){
el.focus();
}
},
color: {
// bind只调用一次, 指令第一次绑定到元素的时候调用, 在这里可以进行一次性的初始化设置。
bind: function(el, binding){
el.style.backgroundColor = binding.value.color;
}
}
}
});
</script>
</body>
</html>
3.2. 效果图