自定义指令
约定,Vue
中所有的指令,在调用的时候,都以v-
开头,实际上,自定义的指令也强制以v-
开头。
一 全局指令
语法:Vue.directive(directivename,{})
在调用自定义指令时,应按照v-directivename
的命名方式进行。
// 注册一个全局自定义指令 v-focus
Vue.directive('focus', {
// 当被绑定的元素插入到 DOM 中时……
inserted: function (el) {
// 聚焦元素,el元素指的是被绑定了指令的那个元素,是一个原生的Dom对象
el.focus()
}
})
钩子函数
一个指令定义对象可以提供如下几个钩子函数 (均为可选):
-
bind
:只调用一次,指令第一次绑定到元素时调用 -
inserted
:被绑定元素插入Dom时调用 -
update
:所在组件的 VNode 更新时调用 -
componentUpdated
:指令所在组件的 VNode 及其子 VNode 全部更新后调用 -
unbind
:只调用一次,指令与元素解绑时调用
举一个例子:
<div id="app">
<input type="text" v-focus v-color>
</div>
<script>
// 行为相关使用inserted
Vue.directive("focus", {
inserted: function (el) {
el.focus();
}
})
// 样式相关使用bind
Vue.directive("color", {
bind: function (el) {
el.style.color = "red"
}
})
var vm = new Vue({
el: "#app",
data: {
msg: "hello"
},
methods: {
}
})
</script>
运行会出现一个处于焦点状态的文本框,且文本为红色。
钩子函数参数
指令钩子函数会被传入以下参数:
el
:指令所绑定的元素,可以用来直接操作 DOM 。binding
:一个对象,包含以下属性:name
:指令名,不包括v-
前缀。value
:指令的绑定值,例如:v-my-directive="1 + 1"
中,绑定值为2
。oldValue
:指令绑定的前一个值,仅在update
和componentUpdated
钩子中可用。无论值是否改变都可用。expression
:字符串形式的指令表达式。例如v-my-directive="1 + 1"
中,表达式为"1 + 1"
。arg
:传给指令的参数,可选。例如v-my-directive:foo
中,参数为"foo"
。modifiers
:一个包含修饰符的对象。例如:v-my-directive.foo.bar
中,修饰符对象为{ foo: true, bar: true }
。
vnode
:Vue 编译生成的虚拟节点。oldVnode
:上一个虚拟节点,仅在update
和componentUpdated
钩子中可用。
<body>
<div id="app">
<input type="text" v-focus v-color:green>
</div>
<script>
Vue.directive("focus", {
inserted: function (el) {
el.focus();
}
})
Vue.directive("color", {
bind: function (el, binding) {
el.style.color = binding.arg;
el.value = binding.name;
}
})
var vm = new Vue({
el: "#app",
data: {
msg: "hello"
},
methods: {
}
})
</script>
</body>
二 私有指令
和过滤器类似,私有指令使用例子如下:
<body>
<div id="app">
<input type="text" v-fontweight="'900'" />
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
msg: "hello"
},
methods: {
},
directives: {
"fontweight": {
bind: function (el, binding) {
el.style.fontWeight = binding.value;
}
}
}
})
</script>
</body>
三 简写
在很多时候,你可能想在 bind
和 update
时触发相同行为,而不关心其它的钩子。可以简写为:
Vue.directive('color', function (el, binding) {
el.style.backgroundColor = binding.value
})
directives: {
"fontweight":
function (el, binding) {
el.style.fontWeight = binding.value;
}
}