vue动态指令

自定义定位的指令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* 简写 l:left; r:rihgt; b:bottom; t:top; z:z-index; bg:background; w:widht; h:height;
* w、h的值根据top.left.right.bottom来进行设置
* <div v-pos:top.left="data"></div>
* data: {
t:0,
l:0,
w:50,
h:50,
bg:'red',
z:9
}
*/

Vue.directive('position', {
bind: function (el, binding, vnode) {
el.style.position = 'fixed'
var pos1 = ['left', 'right', 'bottom', 'top'].includes(binding.arg) ? binding.arg : 'left'
el.style[pos1] = (binding.value[pos1.substring(0,1)] || '0') + 'px'
el.style.background = binding.value.bg || 'red'
binding.value.w && (el.style.width = binding.value.w + 'px')
binding.value.h && (el.style.height = binding.value.h + 'px')
el.style.zIndex = binding.value.z || '0'
let pos2 = Object.keys(binding.modifiers)
pos2.map(p=>{
el.style[p] = (binding.value[p.substring(0, 1)] || '0') + 'px'
})
}
})