8.1 基本用法
自定义指令的注册方法和组件很像。
Vue.directive(‘focus’,{
//指令选项
});
自定义指令的选项是由几个钩子函数组成的:
* bind
* inserted
* update
* componentUpdated
* unbind
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<input type="text" v-focus>
</div>
<script src="../vue.js"></script>
<script>
Vue.directive('focus',{
inserted : function (el) {
//聚焦元素
el.focus();
}
});
var app = new Vue({
el : '#app'
});
</script>
</body>
</html>
每个钩子函数都有下述参数可用:
* el
* binding
1 name
2 value
3 oldValue
4 expression
5 arg
6 modifiers
* vnode
* oldVnode
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<div v-test:msg.a.b="message"></div>
</div>
<script src="../vue.js"></script>
<script>
Vue.directive('test',{
bind : function (el,binding,vnode) {
var keys = [];
for (var i in vnode) {
keys.push(i);
}
el.innerHTML =
'name: ' + binding.name + '<br>' +
'value: ' + binding.value + '<br>' +
'expression: ' + binding.expression + '<br>' +
'argument: ' + binding.arg + '<br>' +
'modifiers: ' + JSON.stringify(binding.modifiers) + '<br>' +
'vnode keys: ' + keys.join(', ')
}
});
var app = new Vue({
el : '#app',
data : {
message : 'some text'
}
});
</script>
</body>
</html>
8.2 实战
1 开发一个可从外部关闭的下拉菜单
2 开发一个实时时间转换指令v-time