本文在github作了收錄 github.com/Michael-lzg…javascript
demo源碼地址 github.com/Michael-lzg…html
在 Vue,除了核心功能默認內置的指令 ( v-model 和 v-show ),Vue 也容許註冊自定義指令。它的做用價值在於當開發人員在某些場景下須要對普通 DOM 元素進行操做。vue
Vue 自定義指令有全局註冊和局部註冊兩種方式。先來看看註冊全局指令的方式,經過 Vue.directive( id, [definition] )
方式註冊全局指令。而後在入口文件中進行 Vue.use()
調用。java
批量註冊指令,新建 directives/index.js
文件node
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
引入並調用webpack
import Vue from 'vue'
import Directives from './JS/directives'
Vue.use(Directives)
複製代碼
指令定義函數提供了幾個鉤子函數(可選):git
下面分享幾個實用的 Vue 自定義指令github
v-copy
v-longpress
v-debounce
v-emoji
v-LazyLoad
v-premission
v-waterMarker
v-draggable
需求:實現一鍵複製文本內容,用於鼠標右鍵粘貼。web
思路:正則表達式
textarea
標籤,並設置 readOnly
屬性及移出可視區域textarea
標籤的 value
屬性,並插入到 body
textarea
並複製body
中插入的 textarea
移除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
及複製的文本便可
<template>
<button v-copy="copyText">複製</button>
</template>
<script> export default { data() { return { copyText: 'a copy directives', } }, } </script>
複製代碼
需求:實現長按,用戶須要按下並按住按鈕幾秒鐘,觸發相應的事件
思路:
mousedown
事件,啓動計時器;用戶鬆開按鈕時調用 mouseout
事件。mouseup
事件 2 秒內被觸發,就清除計時器,看成一個普通的點擊事件touchstart
,touchend
事件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
及回調函數便可
<template>
<button v-longpress="longpress">長按</button>
</template>
<script> export default { methods: { longpress () { alert('長按指令生效') } } } </script>
複製代碼
背景:在開發中,有些提交保存按鈕有時候會在短期內被點擊屢次,這樣就會屢次重複請求後端接口,形成數據的混亂,好比新增表單的提交按鈕,屢次點擊就會新增多條重複的數據。
需求:防止按鈕在短期內被屢次點擊,使用防抖函數限制規定時間內只能點擊一次。
思路:
const debounce = {
inserted: function (el, binding) {
let timer
el.addEventListener('click', () => {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
binding.value()
}, 1000)
})
},
}
export default debounce
複製代碼
使用:給 Dom 加上 v-debounce
及回調函數便可
<template>
<button v-debounce="debounceClick">防抖</button>
</template>
<script> export default { methods: { debounceClick () { console.log('只觸發一次') } } } </script>
複製代碼
背景:開發中遇到的表單輸入,每每會有對輸入內容的限制,好比不能輸入表情和特殊字符,只能輸入數字或字母等。
咱們常規方法是在每個表單的 on-change
事件上作處理。
<template>
<input type="text" v-model="note" @change="vaidateEmoji" />
</template>
<script> export default { methods: { vaidateEmoji() { var reg = /[^\u4E00-\u9FA5|\d|\a-zA-Z|\r\n\s,.?!,。?!…—&$=()-+/*{}[\]]|\s/g this.note = this.note.replace(reg, '') }, }, } </script>
複製代碼
這樣代碼量比較大並且很差維護,因此咱們須要自定義一個指令來解決這問題。
需求:根據正則表達式,設計自定義處理表單輸入規則的指令,下面以禁止輸入表情和特殊字符爲例。
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|\r\n\s,.?!,。?!…—&$=()-+/*{}[\]]|\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
便可
<template>
<input type="text" v-model="note" v-emoji />
</template>
複製代碼
背景:在類電商類項目,每每存在大量的圖片,如 banner 廣告圖,菜單導航圖,美團等商家列表頭圖等。圖片衆多以及圖片體積過大每每會影響頁面加載速度,形成不良的用戶體驗,因此進行圖片懶加載優化勢在必行。
需求:實現一個圖片懶加載指令,只加載瀏覽器可見區域的圖片。
思路:
src
屬性,不然顯示默認圖片圖片懶加載有兩種方式能夠實現,一是綁定 srcoll
事件進行監聽,二是使用 IntersectionObserver
判斷圖片是否到了可視區域,可是有瀏覽器兼容性問題。
下面封裝一個懶加載指令兼容兩種方法,判斷瀏覽器是否支持 IntersectionObserver
API,若是支持就使用 IntersectionObserver
實現懶加載,不然則使用 srcoll
事件監聽 + 節流的方法實現。
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
<img v-LazyLoad="xxx.jpg" />
複製代碼
背景:在一些後臺管理系統,咱們可能須要根據用戶角色進行一些操做權限的判斷,不少時候咱們都是粗暴地給一個元素添加 v-if / v-show
來進行顯示隱藏,但若是判斷條件繁瑣且多個地方須要判斷,這種方式的代碼不只不優雅並且冗餘。針對這種狀況,咱們能夠經過全局自定義指令來處理。
需求:自定義一個權限指令,對須要權限判斷的 Dom 進行顯示隱藏。
思路:
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
賦值判斷便可
<div class="btns">
<!-- 顯示 -->
<button v-permission="'1'">權限按鈕1</button>
<!-- 不顯示 -->
<button v-permission="'10'">權限按鈕2</button>
</div>
複製代碼
需求:給整個頁面添加背景水印
思路:
canvas
特性生成 base64
格式的圖片文件,設置其字體大小,顏色等。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
複製代碼
使用,設置水印文案,顏色,字體大小便可
<template>
<div v-waterMarker="{text:'lzg版權全部',textColor:'rgba(180, 180, 180, 0.4)'}"></div>
</template>
複製代碼
效果如圖所示
需求:實現一個拖拽指令,可在頁面可視區域任意拖拽元素。
思路:
(onmousedown)
時記錄目標元素當前的 left
和 top
值。(onmousemove)
時計算每次移動的橫向距離和縱向距離的變化值,並改變元素的 left
和 top
值(onmouseup)
時完成一次拖拽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 便可
<template>
<div class="el-dialog" v-draggable></div>
</template>
複製代碼
全部指令源碼地址 github.com/Michael-lzg…