在 Vue,除了核心功能默認內置的指令 ( v-model 和 v-show ),Vue 也允許注冊自定義指令。它的作用價值在於當開發人員在某些場景下需要對普通 DOM 元素進行操作。
Vue 自定義指令有全局注冊和局部注冊兩種方式。先來看看注冊全局指令的方式,通過 Vue.directive( id, [definition] )
方式注冊全局指令。然后在入口文件中進行 Vue.use()
調用。
批量注冊指令,新建 directives/index.js
文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import
copy from
'./copy'
import
longpress from
'./longpress'
// 自定義指令
const directives = {
copy,
longpress,
}
export
default
{
install(Vue) {
Object.keys(directives).forEach((key) => {
Vue.directive(key, directives[key])
})
},
}
|
在 main.js
引入並調用
1
2
3
|
import
Vue from
'vue'
import
Directives from
'./JS/directives'
Vue.use(Directives)
|
指令定義函數提供了幾個鈎子函數(可選):
- bind: 只調用一次,指令第一次綁定到元素時調用,可以定義一個在綁定時執行一次的初始化動作。
- inserted: 被綁定元素插入父節點時調用(父節點存在即可調用,不必存在於 document 中)。
- update: 被綁定元素所在的模板更新時調用,而不論綁定值是否變化。通過比較更新前后的綁定值。
- componentUpdated: 被綁定元素所在模板完成一次更新周期時調用。
- unbind: 只調用一次, 指令與元素解綁時調用。
下面分享幾個實用的 Vue 自定義指令
- 復制粘貼指令
v-copy
- 長按指令
v-longpress
- 輸入框防抖指令
v-debounce
- 禁止表情及特殊字符
v-emoji
- 圖片懶加載
v-LazyLoad
- 權限校驗指令
v-premission
- 實現頁面水印
v-waterMarker
- 拖拽指令
v-draggable
v-copy
需求:實現一鍵復制文本內容,用於鼠標右鍵粘貼。
思路:
- 動態創建
textarea
標簽,並設置readOnly
屬性及移出可視區域 - 將要復制的值賦給
textarea
標簽的value
屬性,並插入到body
- 選中值
textarea
並復制 - 將
body
中插入的textarea
移除 - 在第一次調用時綁定事件,在解綁時移除事件
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
30
31
32
33
34
35
36
37
38
39
40
41
|
const copy = {
bind(el, { value }) {
el.$value = value
el.handler = () => {
if
(!el.$value) {
// 值為空的時候,給出提示。可根據項目UI仔細設計
console.log(
'無復制內容'
)
return
}
// 動態創建 textarea 標簽
const textarea = document.createElement(
'textarea'
)
// 將該 textarea 設為 readonly 防止 iOS 下自動喚起鍵盤,同時將 textarea 移出可視區域
textarea.readOnly =
'readonly'
textarea.style.position =
'absolute'
textarea.style.left =
'-9999px'
// 將要 copy 的值賦給 textarea 標簽的 value 屬性
textarea.value = el.$value
// 將 textarea 插入到 body 中
document.body.appendChild(textarea)
// 選中值並復制
textarea.select()
const result = document.execCommand(
'Copy'
)
if
(result) {
console.log(
'復制成功'
)
// 可根據項目UI仔細設計
}
document.body.removeChild(textarea)
}
// 綁定點擊事件,就是所謂的一鍵 copy 啦
el.addEventListener(
'click'
, el.handler)
},
// 當傳進來的值更新的時候觸發
componentUpdated(el, { value }) {
el.$value = value
},
// 指令與元素解綁的時候,移除事件綁定
unbind(el) {
el.removeEventListener(
'click'
, el.handler)
},
}
export
default
copy
|
使用:給 Dom 加上 v-copy
及復制的文本即可
1
2
3
4
5
6
7
8
9
10
11
|
<template>
<button v-copy=
"copyText"
>復制</button>
</template>
<script>
export
default
{
data() {
return
{
copyText:
'a copy directives'
,
}
},
} </script>
|
v-longpress
需求:實現長按,用戶需要按下並按住按鈕幾秒鍾,觸發相應的事件
思路:
- 創建一個計時器, 2 秒后執行函數
- 當用戶按下按鈕時觸發
mousedown
事件,啟動計時器;用戶松開按鈕時調用mouseout
事件。 - 如果
mouseup
事件 2 秒內被觸發,就清除計時器,當作一個普通的點擊事件 - 如果計時器沒有在 2 秒內清除,則判定為一次長按,可以執行關聯的函數。
- 在移動端要考慮
touchstart
,touchend
事件
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
const longpress = {
bind:
function
(el, binding, vNode) {
if
(
typeof
binding.value !==
'function'
) {
throw
'callback must be a function'
}
// 定義變量
let
pressTimer =
null
// 創建計時器( 2秒后執行函數 )
let
start = (e) => {
if
(e.type ===
'click'
&& e.button !== 0) {
return
}
if
(pressTimer ===
null
) {
pressTimer = setTimeout(() => {
handler()
}, 2000)
}
}
// 取消計時器
let
cancel = (e) => {
if
(pressTimer !==
null
) {
clearTimeout(pressTimer)
pressTimer =
null
}
}
// 運行函數
const handler = (e) => {
binding.value(e)
}
// 添加事件監聽器
el.addEventListener(
'mousedown'
, start)
el.addEventListener(
'touchstart'
, start)
// 取消計時器
el.addEventListener(
'click'
, cancel)
el.addEventListener(
'mouseout'
, cancel)
el.addEventListener(
'touchend'
, cancel)
el.addEventListener(
'touchcancel'
, cancel)
},
// 當傳進來的值更新的時候觸發
componentUpdated(el, { value }) {
el.$value = value
},
// 指令與元素解綁的時候,移除事件綁定
unbind(el) {
el.removeEventListener(
'click'
, el.handler)
},
}
export
default
longpress
|
使用:給 Dom 加上 v-longpress
及回調函數即可
1
2
3
4
5
6
7
8
9
10
11
|
<template>
<button v-longpress=
"longpress"
>長按</button>
</template>
<script>
export
default
{
methods: {
longpress () {
alert(
'長按指令生效'
)
}
}
} </script>
|
v-debounce
背景:在開發中,有些提交保存按鈕有時候會在短時間內被點擊多次,這樣就會多次重復請求后端接口,造成數據的混亂,比如新增表單的提交按鈕,多次點擊就會新增多條重復的數據。
需求:防止按鈕在短時間內被多次點擊,使用防抖函數限制規定時間內只能點擊一次。
思路:
- 定義一個延遲執行的方法,如果在延遲時間內再調用該方法,則重新計算執行時間。
- 將時間綁定在 click 方法上。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
const debounce = {
inserted:
function
(el, binding) {
let
timer
el.addEventListener(
'keyup'
, () => {
if
(timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
binding.value()
}, 1000)
})
},
}
export
default
debounce
|
使用:給 Dom 加上 v-debounce
及回調函數即可
1
2
3
4
5
6
7
8
9
10
11
|
<template>
<button v-debounce=
"debounceClick"
>防抖</button>
</template>
<script>
export
default
{
methods: {
debounceClick () {
console.log(
'只觸發一次'
)
}
}
} </script>
|
v-emoji
背景:開發中遇到的表單輸入,往往會有對輸入內容的限制,比如不能輸入表情和特殊字符,只能輸入數字或字母等。
我們常規方法是在每一個表單的 on-change
事件上做處理。
1
2
3
4
5
6
7
8
9
10
11
12
|
<template>
<input type=
"text"
v-model=
"note"
@change=
"vaidateEmoji"
/>
</template>
<script>
export
default
{
methods: {
vaidateEmoji() {
var
reg = /[^u4E00-u9FA5|d|a-zA-Z|rns,.?!,。?!…—&$=()-+/*{}[]]|s/g
this
.note =
this
.note.replace(reg,
''
)
},
},
} </script>
|
這樣代碼量比較大而且不好維護,所以我們需要自定義一個指令來解決這問題。
需求:根據正則表達式,設計自定義處理表單輸入規則的指令,下面以禁止輸入表情和特殊字符為例。
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
30
|
let
findEle = (parent, type) => {
return
parent.tagName.toLowerCase() === type ? parent : parent.querySelector(type)
}
const trigger = (el, type) => {
const e = document.createEvent(
'HTMLEvents'
)
e.initEvent(type,
true
,
true
)
el.dispatchEvent(e)
}
const emoji = {
bind:
function
(el, binding, vnode) {
// 正則規則可根據需求自定義
var
regRule = /[^u4E00-u9FA5|d|a-zA-Z|rns,.?!,。?!…—&$=()-+/*{}[]]|s/g
let
$inp = findEle(el,
'input'
)
el.$inp = $inp
$inp.handle =
function
() {
let
val = $inp.value
$inp.value = val.replace(regRule,
''
)
trigger($inp,
'input'
)
}
$inp.addEventListener(
'keyup'
, $inp.handle)
},
unbind:
function
(el) {
el.$inp.removeEventListener(
'keyup'
, el.$inp.handle)
},
}
export
default
emoji
|
使用:將需要校驗的輸入框加上 v-emoji
即可
1
2
3
|
<template>
<input type=
"text"
v-model=
"note"
v-emoji />
</template>
|
v-LazyLoad
背景:在類電商類項目,往往存在大量的圖片,如 banner 廣告圖,菜單導航圖,美團等商家列表頭圖等。圖片眾多以及圖片體積過大往往會影響頁面加載速度,造成不良的用戶體驗,所以進行圖片懶加載優化勢在必行。
需求:實現一個圖片懶加載指令,只加載瀏覽器可見區域的圖片。
思路:
- 圖片懶加載的原理主要是判斷當前圖片是否到了可視區域這一核心邏輯實現的
- 拿到所有的圖片 Dom ,遍歷每個圖片判斷當前圖片是否到了可視區范圍內
- 如果到了就設置圖片的
src
屬性,否則顯示默認圖片
圖片懶加載有兩種方式可以實現,一是綁定 srcoll
事件進行監聽,二是使用 IntersectionObserver
判斷圖片是否到了可視區域,但是有瀏覽器兼容性問題。
下面封裝一個懶加載指令兼容兩種方法,判斷瀏覽器是否支持 IntersectionObserver
API,如果支持就使用 IntersectionObserver
實現懶加載,否則則使用 srcoll
事件監聽 + 節流的方法實現。
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
const LazyLoad = {
// install方法
install(Vue, options) {
const defaultSrc = options.
default
Vue.directive(
'lazy'
, {
bind(el, binding) {
LazyLoad.init(el, binding.value, defaultSrc)
},
inserted(el) {
if
(IntersectionObserver) {
LazyLoad.observe(el)
}
else
{
LazyLoad.listenerScroll(el)
}
},
})
},
// 初始化
init(el, val, def) {
el.setAttribute(
'data-src'
, val)
el.setAttribute(
'src'
, def)
},
// 利用IntersectionObserver監聽el
observe(el) {
var
io =
new
IntersectionObserver((entries) => {
const realSrc = el.dataset.src
if
(entries[0].isIntersecting) {
if
(realSrc) {
el.src = realSrc
el.removeAttribute(
'data-src'
)
}
}
})
io.observe(el)
},
// 監聽scroll事件
listenerScroll(el) {
const handler = LazyLoad.throttle(LazyLoad.load, 300)
LazyLoad.load(el)
window.addEventListener(
'scroll'
, () => {
handler(el)
})
},
// 加載真實圖片
load(el) {
const windowHeight = document.documentElement.clientHeight
const elTop = el.getBoundingClientRect().top
const elBtm = el.getBoundingClientRect().bottom
const realSrc = el.dataset.src
if
(elTop - windowHeight < 0 && elBtm > 0) {
if
(realSrc) {
el.src = realSrc
el.removeAttribute(
'data-src'
)
}
}
},
// 節流
throttle(fn, delay) {
let
timer
let
prevTime
return
function
(...args) {
const currTime = Date.now()
const context =
this
if
(!prevTime) prevTime = currTime
clearTimeout(timer)
if
(currTime - prevTime > delay) {
prevTime = currTime
fn.apply(context, args)
clearTimeout(timer)
return
}
timer = setTimeout(
function
() {
prevTime = Date.now()
timer =
null
fn.apply(context, args)
}, delay)
}
},
}
export
default
LazyLoad
|
使用,將組件內 標簽的 src
換成 v-LazyLoad
1
|
<img v-LazyLoad=
"xxx.jpg"
/>
|
v-permission
背景:在一些后台管理系統,我們可能需要根據用戶角色進行一些操作權限的判斷,很多時候我們都是粗暴地給一個元素添加 v-if / v-show
來進行顯示隱藏,但如果判斷條件繁瑣且多個地方需要判斷,這種方式的代碼不僅不優雅而且冗余。針對這種情況,我們可以通過全局自定義指令來處理。
需求:自定義一個權限指令,對需要權限判斷的 Dom 進行顯示隱藏。
思路:
- 自定義一個權限數組
- 判斷用戶的權限是否在這個數組內,如果是則顯示,否則則移除 Dom
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
function
checkArray(key) {
let
arr = [
'1'
,
'2'
,
'3'
,
'4'
]
let
index = arr.indexOf(key)
if
(index > -1) {
return
true
// 有權限
}
else
{
return
false
// 無權限
}
}
const permission = {
inserted:
function
(el, binding) {
let
permission = binding.value
// 獲取到 v-permission的值
if
(permission) {
let
hasPermission = checkArray(permission)
if
(!hasPermission) {
// 沒有權限 移除Dom元素
el.parentNode && el.parentNode.removeChild(el)
}
}
},
}
export
default
permission
|
使用:給 v-permission
賦值判斷即可
1
2
3
4
5
6
|
<div
class
=
"btns"
>
<!-- 顯示 -->
<button v-permission=
"'1'"
>權限按鈕1</button>
<!-- 不顯示 -->
<button v-permission=
"'10'"
>權限按鈕2</button>
</div>
|
vue-waterMarker
需求:給整個頁面添加背景水印
思路:
- 使用
canvas
特性生成base64
格式的圖片文件,設置其字體大小,顏色等。 - 將其設置為背景圖片,從而實現頁面或組件水印效果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
function
addWaterMarker(str, parentNode, font, textColor) {
// 水印文字,父元素,字體,文字顏色
var
can = document.createElement(
'canvas'
)
parentNode.appendChild(can)
can.width = 200
can.height = 150
can.style.display =
'none'
var
cans = can.getContext(
'2d'
)
cans.rotate((-20 * Math.PI) / 180)
cans.font = font ||
'16px Microsoft JhengHei'
cans.fillStyle = textColor ||
'rgba(180, 180, 180, 0.3)'
cans.textAlign =
'left'
cans.textBaseline =
'Middle'
cans.fillText(str, can.width / 10, can.height / 2)
parentNode.style.backgroundImage =
'url('
+ can.toDataURL(
'image/png'
) +
')'
}
const waterMarker = {
bind:
function
(el, binding) {
addWaterMarker(binding.value.text, el, binding.value.font, binding.value.textColor)
},
}
export
default
waterMarker
|
使用,設置水印文案,顏色,字體大小即可
1
2
3
|
<template>
<div v-waterMarker=
"{text:'lzg版權所有',textColor:'rgba(180, 180, 180, 0.4)'}"
></div>
</template>
|
效果如圖所示
v-draggable
需求:實現一個拖拽指令,可在頁面可視區域任意拖拽元素。
思路:
- 設置需要拖拽的元素為相對定位,其父元素為絕對定位。
- 鼠標按下
(onmousedown)
時記錄目標元素當前的left
和top
值。 - 鼠標移動
(onmousemove)
時計算每次移動的橫向距離和縱向距離的變化值,並改變元素的left
和top
值 - 鼠標松開
(onmouseup)
時完成一次拖拽
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
30
31
32
33
|
const draggable = {
inserted:
function
(el) {
el.style.cursor =
'move'
el.onmousedown =
function
(e) {
let
disx = e.pageX - el.offsetLeft
let
disy = e.pageY - el.offsetTop
document.onmousemove =
function
(e) {
let
x = e.pageX - disx
let
y = e.pageY - disy
let
maxX = document.body.clientWidth - parseInt(window.getComputedStyle(el).width)
let
maxY = document.body.clientHeight - parseInt(window.getComputedStyle(el).height)
if
(x < 0) {
x = 0
}
else
if
(x > maxX) {
x = maxX
}
if
(y < 0) {
y = 0
}
else
if
(y > maxY) {
y = maxY
}
el.style.left = x +
'px'
el.style.top = y +
'px'
}
document.onmouseup =
function
() {
document.onmousemove = document.onmouseup =
null
}
}
},
}
export
default
draggable
|
使用: 在 Dom 上加上 v-draggable 即可
1
2
3
|
<template>
<div
class
=
"el-dialog"
v-draggable></div>
</template>
|