自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

分享8個非常實用的Vue自定義指令

開發(fā) 前端
在 Vue,除了核心功能默認內(nèi)置的指令 ( v-model 和 v-show ),Vue 也允許注冊 自定義指令。它的作用價值在于當(dāng)開發(fā)人員在某些場景下需要對普通 DOM 元素進行操作。

 [[360453]]

【導(dǎo)讀】:入門級范例,結(jié)合Vue文檔使用更佳。推薦用于新手學(xué)習(xí),不推薦直接用于生產(chǎn)環(huán)境。

在 Vue,除了核心功能默認內(nèi)置的指令 ( v-model 和 v-show ),Vue 也允許注冊  自定義指令。它的作用價值在于當(dāng)開發(fā)人員在某些場景下需要對普通 DOM 元素進行操作。

Vue 自定義指令有全局注冊和局部注冊兩種方式。先來看看注冊全局指令的方式,通過 Vue.directive( id, [definition] ) 方式注冊全局指令。然后在入口文件中進行 Vue.use() 調(diào)用。

批量注冊指令,新建 directives/index.js 文件 

  1. import copy from './copy'  
  2. import longpress from './longpress'  
  3. // 自定義指令  
  4. const directives = {  
  5.   copy,  
  6.   longpress,  
  7.  
  8. export default {  
  9.   install(Vue) {  
  10.     Object.keys(directives).forEach((key) => {  
  11.       Vue.directive(key, directives[key])  
  12.     })  
  13.   },  
  14.  
  15. 復(fù)制代碼 

在 main.js 引入并調(diào)用 

  1. import Vue from 'vue'  
  2. import Directives from './JS/directives'  
  3. Vue.use(Directives)  
  4. 復(fù)制代碼 

指令定義函數(shù)提供了幾個鉤子函數(shù)(可選):

  •  bind: 只調(diào)用一次,指令第一次綁定到元素時調(diào)用,可以定義一個在綁定時執(zhí)行一次的初始化動作。
  •  inserted: 被綁定元素插入父節(jié)點時調(diào)用(父節(jié)點存在即可調(diào)用,不必存在于 document 中)。
  •  update: 被綁定元素所在的模板更新時調(diào)用,而不論綁定值是否變化。通過比較更新前后的綁定值。
  •  componentUpdated: 被綁定元素所在模板完成一次更新周期時調(diào)用。
  •  unbind: 只調(diào)用一次, 指令與元素解綁時調(diào)用。

下面分享幾個實用的 Vue 自定義指令

  •  復(fù)制粘貼指令 v-copy
  •  長按指令 v-longpress
  •  輸入框防抖指令 v-debounce
  •  禁止表情及特殊字符 v-emoji
  •  圖片懶加載 v-LazyLoad
  •  權(quán)限校驗指令 v-premission
  •  實現(xiàn)頁面水印 v-waterMarker
  •  拖拽指令 v-draggable

v-copy

需求:實現(xiàn)一鍵復(fù)制文本內(nèi)容,用于鼠標右鍵粘貼。

思路:

1.動態(tài)創(chuàng)建 textarea 標簽,并設(shè)置 readOnly 屬性及移出可視區(qū)域

2.將要復(fù)制的值賦給 textarea 標簽的 value 屬性,并插入到 body

3.選中值 textarea 并復(fù)制 4.將 body 中插入的 textarea 移除

5.在第一次調(diào)用時綁定事件,在解綁時移除事件 

  1. const copy = {  
  2.   bind(el, { value }) {  
  3.     el.$valuevalue = value  
  4.     el.handler = () => { 
  5.        if (!el.$value) {  
  6.         // 值為空的時候,給出提示。可根據(jù)項目UI仔細設(shè)計  
  7.         console.log('無復(fù)制內(nèi)容')  
  8.         return  
  9.       }  
  10.       // 動態(tài)創(chuàng)建 textarea 標簽  
  11.       const textarea = document.createElement('textarea')  
  12.       // 將該 textarea 設(shè)為 readonly 防止 iOS 下自動喚起鍵盤,同時將 textarea 移出可視區(qū)域  
  13.       textarea.readOnly = 'readonly'  
  14.       textarea.style.position = 'absolute'  
  15.       textarea.style.left = '-9999px'  
  16.       // 將要 copy 的值賦給 textarea 標簽的 value 屬性  
  17.       textarea.value = el.$value  
  18.       // 將 textarea 插入到 body 中  
  19.       document.body.appendChild(textarea)  
  20.       // 選中值并復(fù)制  
  21.       textarea.select()  
  22.       const result = document.execCommand('Copy')  
  23.       if (result) {  
  24.         console.log('復(fù)制成功') // 可根據(jù)項目UI仔細設(shè)計  
  25.       }  
  26.       document.body.removeChild(textarea)  
  27.     }  
  28.     // 綁定點擊事件,就是所謂的一鍵 copy 啦  
  29.     el.addEventListener('click', el.handler)  
  30.   },  
  31.   // 當(dāng)傳進來的值更新的時候觸發(fā)  
  32.   componentUpdated(el, { value }) {  
  33.     el.$valuevalue = value  
  34.   },  
  35.   // 指令與元素解綁的時候,移除事件綁定  
  36.   unbind(el) {  
  37.     el.removeEventListener('click', el.handler)  
  38.   },  
  39.  
  40. export default copy  
  41. 復(fù)制代碼 

使用:給 Dom 加上 v-copy 及復(fù)制的文本即可 

  1. <template>  
  2.   <button v-copy="copyText">復(fù)制</button>  
  3. </template>  
  4. <script>  
  5.   export default {  
  6.     data() {  
  7.       return {  
  8.         copyText: 'a copy directives',  
  9.       }  
  10.     },  
  11.   }  
  12. </script>  
  13. 復(fù)制代碼 

v-longpress

需求:實現(xiàn)長按,用戶需要按下并按住按鈕幾秒鐘,觸發(fā)相應(yīng)的事件

思路:

1.創(chuàng)建一個計時器, 2 秒后執(zhí)行函數(shù)

2.當(dāng)用戶按下按鈕時觸發(fā) mousedown 事件,啟動計時器;用戶松開按鈕時調(diào)用 mouseout 事件。

3.如果 mouseup 事件 2 秒內(nèi)被觸發(fā),就清除計時器,當(dāng)作一個普通的點擊事件

4.如果計時器沒有在 2 秒內(nèi)清除,則判定為一次長按,可以執(zhí)行關(guān)聯(lián)的函數(shù)。

5.在移動端要考慮 touchstart,touchend 事件 

  1. const longpress = {  
  2.   bind: function (el, binding, vNode) {  
  3.     if (typeof binding.value !== 'function') {  
  4.       throw 'callback must be a function'  
  5.     }  
  6.     // 定義變量  
  7.     let pressTimer = null  
  8.     // 創(chuàng)建計時器( 2秒后執(zhí)行函數(shù) )  
  9.     let start = (e) => {  
  10.       if (e.type === 'click' && e.button !== 0) {  
  11.         return  
  12.       }  
  13.       if (pressTimer === null) {  
  14.         pressTimer = setTimeout(() => {  
  15.           handler()  
  16.         }, 2000)  
  17.       }  
  18.     }  
  19.     // 取消計時器  
  20.     let cancel = (e) => {  
  21.       if (pressTimer !== null) {  
  22.         clearTimeout(pressTimer)  
  23.         pressTimer = null  
  24.       }  
  25.     }  
  26.     // 運行函數(shù)  
  27.     const handler = (e) => { 
  28.        binding.value(e)  
  29.     }  
  30.     // 添加事件監(jiān)聽器  
  31.     el.addEventListener('mousedown', start)  
  32.     el.addEventListener('touchstart', start)  
  33.     // 取消計時器  
  34.     el.addEventListener('click', cancel)  
  35.     el.addEventListener('mouseout', cancel)  
  36.     el.addEventListener('touchend', cancel)  
  37.     el.addEventListener('touchcancel', cancel)  
  38.   },  
  39.   // 當(dāng)傳進來的值更新的時候觸發(fā)  
  40.   componentUpdated(el, { value }) {  
  41.     el.$valuevalue = value  
  42.   },  
  43.   // 指令與元素解綁的時候,移除事件綁定  
  44.   unbind(el) {  
  45.     el.removeEventListener('click', el.handler)  
  46.   },  
  47.  
  48. export default longpress  
  49. 復(fù)制代碼 

使用:給 Dom 加上 v-longpress 及回調(diào)函數(shù)即可 

  1. <template>  
  2.   <button v-longpress="longpress">長按</button>  
  3. </template>  
  4. <script>  
  5. export default {  
  6.   methods: {  
  7.     longpress () {  
  8.       alert('長按指令生效')  
  9.     }  
  10.   }  
  11.  </script>  
  12. 復(fù)制代碼 

v-debounce

背景:在開發(fā)中,有些提交保存按鈕有時候會在短時間內(nèi)被點擊多次,這樣就會多次重復(fù)請求后端接口,造成數(shù)據(jù)的混亂,比如新增表單的提交按鈕,多次點擊就會新增多條重復(fù)的數(shù)據(jù)。

需求:防止按鈕在短時間內(nèi)被多次點擊,使用防抖函數(shù)限制規(guī)定時間內(nèi)只能點擊一次。

思路:

1.定義一個延遲執(zhí)行的方法,如果在延遲時間內(nèi)再調(diào)用該方法,則重新計算執(zhí)行時間。

2.將事件綁定在 click 方法上。 

  1. const debounce = {  
  2.   inserted: function (el, binding) {  
  3.     let timer  
  4.     el.addEventListener('click', () => {  
  5.       if (timer) {  
  6.         clearTimeout(timer)  
  7.       }  
  8.       timer = setTimeout(() => {  
  9.         binding.value()  
  10.       }, 1000)  
  11.     })  
  12.   },  
  13.  
  14. export default debounce  
  15. 復(fù)制代碼 

使用:給 Dom 加上 v-debounce 及回調(diào)函數(shù)即可 

  1. <template>  
  2.   <button v-debounce="debounceClick">防抖</button>  
  3. </template>  
  4. <script>  
  5. export default {  
  6.   methods: {  
  7.     debounceClick () {  
  8.       console.log('只觸發(fā)一次')  
  9.     }  
  10.   }  
  11.  
  12. </script>  
  13. 復(fù)制代碼 

v-emoji

背景:開發(fā)中遇到的表單輸入,往往會有對輸入內(nèi)容的限制,比如不能輸入表情和特殊字符,只能輸入數(shù)字或字母等。

我們常規(guī)方法是在每一個表單的 on-change 事件上做處理。 

  1. <template>  
  2.   <input type="text" v-model="note" @change="vaidateEmoji" />  
  3. </template>  
  4. <script>  
  5.   export default {  
  6.     methods: {  
  7.       vaidateEmoji() {  
  8.         var reg = /[^\u4E00-\u9FA5|\d|\a-zA-Z|\r\n\s,.?!,。?!…—&$=()-+/*{}[\]]|\s/g  
  9.         thisthis.note = this.note.replace(reg, '')  
  10.       },  
  11.     },  
  12.   }  
  13. </script>  
  14. 復(fù)制代碼 

這樣代碼量比較大而且不好維護,所以我們需要自定義一個指令來解決這問題。

需求:根據(jù)正則表達式,設(shè)計自定義處理表單輸入規(guī)則的指令,下面以禁止輸入表情和特殊字符為例。 

  1. let findEle = (parent, type) => {  
  2.   return parent.tagName.toLowerCase() === type ? parent : parent.querySelector(type)  
  3.  
  4. const trigger = (el, type) => {  
  5.   const e = document.createEvent('HTMLEvents')  
  6.   e.initEvent(type, true, true)  
  7.   el.dispatchEvent(e)  
  8.  
  9. const emoji = {  
  10.   bind: function (el, binding, vnode) {  
  11.     // 正則規(guī)則可根據(jù)需求自定義  
  12.     var regRule = /[^\u4E00-\u9FA5|\d|\a-zA-Z|\r\n\s,.?!,。?!…—&$=()-+/*{}[\]]|\s/g  
  13.     let $inp = findEle(el, 'input')  
  14.     el.$inp = $inp  
  15.     $inp.handle = function () {  
  16.       let val = $inp.value  
  17.       $inp.value = val.replace(regRule, '')  
  18.       trigger($inp, 'input')  
  19.     }  
  20.     $inp.addEventListener('keyup', $inp.handle)  
  21.   },  
  22.   unbind: function (el) { 
  23.      el.$inp.removeEventListener('keyup', el.$inp.handle)  
  24.   },  
  25.  
  26. export default emoji  
  27. 復(fù)制代碼 

使用:將需要校驗的輸入框加上 v-emoji 即可 

  1. <template>  
  2.   <input type="text" v-model="note" v-emoji />  
  3. </template>  
  4. 復(fù)制代碼 

v-LazyLoad

背景:在類電商類項目,往往存在大量的圖片,如 banner 廣告圖,菜單導(dǎo)航圖,美團等商家列表頭圖等。圖片眾多以及圖片體積過大往往會影響頁面加載速度,造成不良的用戶體驗,所以進行圖片懶加載優(yōu)化勢在必行。

需求:實現(xiàn)一個圖片懶加載指令,只加載瀏覽器可見區(qū)域的圖片。

思路:

  1.  圖片懶加載的原理主要是判斷當(dāng)前圖片是否到了可視區(qū)域這一核心邏輯實現(xiàn)的
  2.  拿到所有的圖片 Dom ,遍歷每個圖片判斷當(dāng)前圖片是否到了可視區(qū)范圍內(nèi)
  3.  如果到了就設(shè)置圖片的 src 屬性,否則顯示默認圖片

圖片懶加載有兩種方式可以實現(xiàn),一是綁定 srcoll 事件進行監(jiān)聽,二是使用 IntersectionObserver 判斷圖片是否到了可視區(qū)域,但是有瀏覽器兼容性問題。

下面封裝一個懶加載指令兼容兩種方法,判斷瀏覽器是否支持 IntersectionObserver API,如果支持就使用 IntersectionObserver 實現(xiàn)懶加載,否則則使用 srcoll 事件監(jiān)聽 + 節(jié)流的方法實現(xiàn)。 

  1. const LazyLoad = {  
  2.   // install方法  
  3.   install(Vue, options) {  
  4.     const defaultSrc = options.default  
  5.     Vue.directive('lazy', {  
  6.       bind(el, binding) {  
  7.         LazyLoad.init(el, binding.value, defaultSrc)  
  8.       },  
  9.       inserted(el) {  
  10.         if (IntersectionObserver) {  
  11.           LazyLoad.observe(el)  
  12.         } else {  
  13.           LazyLoad.listenerScroll(el)  
  14.         }  
  15.       },  
  16.     })  
  17.   },  
  18.   // 初始化  
  19.   init(el, val, def) {  
  20.     el.setAttribute('data-src', val)  
  21.     el.setAttribute('src', def)  
  22.   },  
  23.   // 利用IntersectionObserver監(jiān)聽el  
  24.   observe(el) {  
  25.     var io = new IntersectionObserver((entries) => {  
  26.       const realSrc = el.dataset.src  
  27.       if (entries[0].isIntersecting) {  
  28.         if (realSrc) {  
  29.           el.src = realSrc  
  30.           el.removeAttribute('data-src')  
  31.         } 
  32.       }  
  33.     })  
  34.     io.observe(el)  
  35.   },  
  36.   // 監(jiān)聽scroll事件  
  37.   listenerScroll(el) {  
  38.     const handler = LazyLoad.throttle(LazyLoad.load, 300)  
  39.     LazyLoad.load(el)  
  40.     window.addEventListener('scroll', () => {  
  41.       handler(el) 
  42.     })  
  43.   },  
  44.   // 加載真實圖片  
  45.   load(el) {  
  46.     const windowHeight = document.documentElement.clientHeight  
  47.     const elelTop = el.getBoundingClientRect().top  
  48.     const elelBtm = el.getBoundingClientRect().bottom  
  49.     const realSrc = el.dataset.src  
  50.     if (elTop - windowHeight < 0 && elBtm > 0) {  
  51.       if (realSrc) {  
  52.         el.src = realSrc  
  53.         el.removeAttribute('data-src')  
  54.       }  
  55.     }  
  56.   },  
  57.   // 節(jié)流  
  58.   throttle(fn, delay) {  
  59.     let timer  
  60.     let prevTime  
  61.     return function (...args) {  
  62.       const currTime = Date.now()  
  63.       const context = this  
  64.       if (!prevTime) prevTime = currTime  
  65.       clearTimeout(timer)  
  66.       if (currTime - prevTime > delay) {  
  67.         prevTime = currTime  
  68.         fn.apply(context, args)  
  69.         clearTimeout(timer)  
  70.         return  
  71.       }  
  72.       timer = setTimeout(function () {  
  73.         prevTime = Date.now()  
  74.         timer = null  
  75.         fn.apply(context, args)  
  76.       }, delay)  
  77.     }  
  78.   },  
  79.  
  80. export default LazyLoad  
  81. 復(fù)制代碼 

使用,將組件內(nèi)  標簽的 src 換成 v-LazyLoad 

  1. <img v-LazyLoad="xxx.jpg" />  
  2. 復(fù)制代碼 

v-permission

背景:在一些后臺管理系統(tǒng),我們可能需要根據(jù)用戶角色進行一些操作權(quán)限的判斷,很多時候我們都是粗暴地給一個元素添加 v-if / v-show 來進行顯示隱藏,但如果判斷條件繁瑣且多個地方需要判斷,這種方式的代碼不僅不優(yōu)雅而且冗余。針對這種情況,我們可以通過全局自定義指令來處理。

需求:自定義一個權(quán)限指令,對需要權(quán)限判斷的 Dom 進行顯示隱藏。

思路:

1.自定義一個權(quán)限數(shù)組

2.判斷用戶的權(quán)限是否在這個數(shù)組內(nèi),如果是則顯示,否則則移除 Dom 

  1. function checkArray(key) {  
  2.   let arr = ['1', '2', '3', '4']  
  3.   let index = arr.indexOf(key)  
  4.   if (index > -1) {  
  5.     return true // 有權(quán)限  
  6.   } else {  
  7.     return false // 無權(quán)限  
  8.  }  
  9.  
  10. const permission = {  
  11.   inserted: function (el, binding) {  
  12.     let permission = binding.value // 獲取到 v-permission的值  
  13.     if (permission) {  
  14.       let hasPermission = checkArray(permission)  
  15.       if (!hasPermission) {  
  16.         // 沒有權(quán)限 移除Dom元素  
  17.         el.parentNode && el.parentNode.removeChild(el)  
  18.       }  
  19.     }  
  20.   },  
  21.    
  22. export default permission  
  23. 復(fù)制代碼 

使用:給 v-permission 賦值判斷即可 

  1. <div class="btns">  
  2.   <!-- 顯示 --> 
  3.    <button v-permission="'1'">權(quán)限按鈕1</button>  
  4.   <!-- 不顯示 -->  
  5.   <button v-permission="'10'">權(quán)限按鈕2</button>  
  6. </div>  
  7. 復(fù)制代碼 

vue-waterMarker

需求:給整個頁面添加背景水印

思路:

1.使用 canvas 特性生成 base64 格式的圖片文件,設(shè)置其字體大小,顏色等。

2.將其設(shè)置為背景圖片,從而實現(xiàn)頁面或組件水印效果 

  1. function addWaterMarker(str, parentNode, font, textColor) {  
  2.   // 水印文字,父元素,字體,文字顏色  
  3.   var can = document.createElement('canvas')  
  4.   parentNode.appendChild(can)  
  5.   can.width = 200  
  6.   can.height = 150  
  7.   can.style.display = 'none'  
  8.   var cancans = can.getContext('2d')  
  9.   cans.rotate((-20 * Math.PI) / 180)  
  10.   cans.font = font || '16px Microsoft JhengHei'  
  11.   cans.fillStyle = textColor || 'rgba(180, 180, 180, 0.3)'  
  12.   cans.textAlign = 'left'  
  13.   cans.textBaseline = 'Middle'  
  14.   cans.fillText(str, can.width / 10, can.height / 2)  
  15.   parentNode.style.backgroundImage = 'url(' + can.toDataURL('image/png') + ')'  
  16.  
  17. const waterMarker = {  
  18.   bind: function (el, binding) {  
  19.     addWaterMarker(binding.value.text, el, binding.value.font, binding.value.textColor)  
  20.   },  
  21.   
  22. export default waterMarker  
  23. 復(fù)制代碼 

使用,設(shè)置水印文案,顏色,字體大小即可 

  1. <template>  
  2.   <div v-waterMarker="{text:'lzg版權(quán)所有',textColor:'rgba(180, 180, 180, 0.4)'}"></div>  
  3. </template>  
  4. 復(fù)制代碼 

v-draggable

需求:實現(xiàn)一個拖拽指令,可在頁面可視區(qū)域任意拖拽元素。

思路:

1.設(shè)置需要拖拽的元素為相對定位,其父元素為絕對定位。

2.鼠標按下(onmousedown)時記錄目標元素當(dāng)前的 left 和 top 值。

3.鼠標移動(onmousemove)時計算每次移動的橫向距離和縱向距離的變化值,并改變元素的 left 和 top 值

4.鼠標松開(onmouseup)時完成一次拖拽 

  1. const draggable = {  
  2.   inserted: function (el) {  
  3.     el.style.cursor = 'move'  
  4.     el.onmousedown = function (e) {  
  5.       let disx = e.pageX - el.offsetLeft  
  6.       let disy = e.pageY - el.offsetTop  
  7.       document.onmousemove = function (e) {  
  8.         let x = e.pageX - disx 
  9.          let y = e.pageY - disy  
  10.         let maxX = document.body.clientWidth - parseInt(window.getComputedStyle(el).width)  
  11.         let maxY = document.body.clientHeight - parseInt(window.getComputedStyle(el).height)  
  12.         if (x < 0) {  
  13.           x = 0  
  14.         } else if (x > maxX) { 
  15.            x = maxX  
  16.         }  
  17.         if (y < 0) {  
  18.           y = 0  
  19.         } else if (y > maxY) {  
  20.           y = maxY  
  21.         } 
  22.         el.style.left = x + 'px'  
  23.         el.style.top = y + 'px'  
  24.       }  
  25.       document.onmouseup = function () {  
  26.         documentdocument.onmousemove = document.onmouseup = null  
  27.       } 
  28.     }  
  29.   },  
  30.  
  31. export default draggable  
  32. 復(fù)制代碼 

使用: 在 Dom 上加上 v-draggable 即可 

  1. <template>  
  2.   <div class="el-dialog" v-draggable></div>  
  3. </template>  
  4. 復(fù)制代碼 

所有指令源碼地址 https://github.com/Michael-lzg/v-directives 

 

責(zé)任編輯:龐桂玉 來源: 前端大全
相關(guān)推薦

2022-02-22 13:14:30

Vue自定義指令注冊

2021-07-05 15:35:47

Vue前端代碼

2023-06-28 08:05:46

場景vue3自定義

2021-11-30 08:19:43

Vue3 插件Vue應(yīng)用

2023-07-21 19:16:59

OpenAIChatGPT

2023-03-07 16:09:08

2022-07-26 01:06:18

Vue3自定義指令

2023-09-27 22:10:47

Vue.jsJavaScript

2022-04-08 08:11:44

自定義鉤子Vuejs

2019-09-26 14:56:18

GitHub 技術(shù)開源

2023-01-28 23:23:51

軟件監(jiān)測工具

2011-08-01 10:36:35

CSS

2023-08-03 07:05:28

電腦軟件工具

2024-09-26 14:16:07

2020-11-05 09:38:44

Linux 系統(tǒng) 數(shù)據(jù)工具

2023-10-30 08:35:50

水波紋效果vue

2015-11-02 09:25:07

jQuery代碼片段

2017-12-12 14:50:33

數(shù)據(jù)庫MySQL命令

2016-05-10 10:16:13

JavaScript技巧

2022-12-06 17:18:42

點贊
收藏

51CTO技術(shù)棧公眾號