自定义指令主要有两种方式。
一是在组件里以directives的选项来自定义指令的内容。这样的自定义指令是局部的自定义指令,只在当前的组件里面才能使用。
<
script
>
export
default {
data(){
},
directives: {
myOrder: {
inserted(
el ,
bind){
let
styleObj =
bind.
value;
let
arr = [];
for(
let
key
in
styleObj){
arr.
push(
key +
':' +
styleObj[
key])
};
arr =
arr.
join(
';');
el.
style.
cssText =
arr;
}
}
}
}
</
script
>
二是在全局注册,用Vue.directive('name',{})的方式自定义指令。
Vue.
directive(
'myOrder' , {
//inserted是一个钩子函数,指明在有这个指令的元素的什么阶段做什么事情。常用的钩子函数有inserted,bind等
//钩子函数的参数:el是绑定指令的元素,bind是指令的内容
inserted(
el ,
bind){
let
styleObj =
bind.
value;
let
arr = [];
for(
let
key
in
styleObj){
arr.
push(
key +
':' +
styleObj[
key])
};
arr =
arr.
join(
';');
el.
style.
cssText =
arr;
}
})
指令中常用的钩子函数有inserted,bind等。
上面的指令功能:设置css样式
<
p
v-myOrder="{
color :
'red'}"
>hello , world
</
p
>