Vue 自定義指令詳解
首先,我們知道vue中有很多自帶指令,v-bind、v-on、v-model等。但在業(yè)務開發(fā)中,我們常見一些自定義指令如:v-copy、v-longpress等。那么如何定義自己所需的指令呢?
接下來我們分別從指令注冊、指令的鉤子函數、指令的參數以及常見指令的封裝進行介紹
為什么要自定義指令
在使用vue的時候 我們某些場景下仍然需要對普通 DOM 元素進行底層操作,
在vue中、組件渲染需要時間,獲取DOM常需要搭配setTimeout、$nextTick使用
而自定義指令在使用時,更便捷。
指令注冊
指令的注冊命令:Vue.directive(key, directives[key])
使用:Vue.use()
全局注冊
在我們常見的項目結構中、directives文件夾下,定義的index.js文件中,我們會對指令進行全局注冊。
import MyDirective from './directive/myDirective' const directives = { MyDirective } export default { install(app) { // 遍歷、注冊 Object.keys(directives).forEach((key) => { app.directive(key, directives[key]) }) } }
局部注冊
在你自己組件或頁面中,使用directives選項自定義指令
export default { directives: { myDirective: { inserted: function (el) { // } } } }
使用
<input v-myDirective>
添加參數v-myDirective="data"
傳遞數值給指令,這里的data可以是組件中的data數據,也可以是methods方法。
<div v-myDirective="{ color: 'white', text: 'hello!' }"></div> app.directive('myDirective', (el, binding) => { console.log(binding.value.color) // => "white" console.log(binding.value.text) // => "hello!" })
v-myDirective:click="clickHandle"
,傳遞參數click,這里可以通過[xx]的格式動態(tài)傳遞參數。v-myDirective:click.top.bar="clickHandle"
傳遞修飾符top和bar。
注意:不推薦在組件上使用自定義指令、它會應用于組件的根結點、和透傳 attributes 類似。
指令的鉤子和參數
const myDirective = { // 在綁定元素的 attribute 前 // 或事件監(jiān)聽器應用前調用 created(el, binding, vnode) { // 下面會介紹各個參數的細節(jié) }, // 在元素被插入到 DOM 前調用 beforeMount(el, binding, vnode) {}, // 在綁定元素的父組件 // 及他自己的所有子節(jié)點都掛載完成后調用 mounted(el, binding, vnode) {}, // 綁定元素的父組件更新前調用 beforeUpdate(el, binding, vnode, prevVnode) {}, // 在綁定元素的父組件 // 及他自己的所有子節(jié)點都更新后調用 updated(el, binding, vnode, prevVnode) {}, // 綁定元素的父組件卸載前調用 beforeUnmount(el, binding, vnode) {}, // 綁定元素的父組件卸載后調用 unmounted(el, binding, vnode) {} }
- bind: 只調用一次,指令第一次綁定到HTML元素時調用,可以定義一個在綁定時執(zhí)行一次的初始化動作,此時獲取父節(jié)點為null。
bind: function (el, {value:{fn,time}}) {}
- el:指令綁定的元素、用來操作DOM
- value:指令的綁定值inserted: 被綁定元素插入父節(jié)點時調用,此時可以獲取到父節(jié)點。
- update: 所在組件的VNode更新時調用,但是可能發(fā)生在其子 VNode 更新之前。指令的值可能發(fā)生了改變,也可能沒有。但是你可以通過比較更新前后的值來忽略不必要的模板更新componentUpdated: 指令所在組件的 VNode 及其子 VNode 全部更新后調用。
unbind: 只調用一次, 指令與元素解綁時調用。
常見指令的封裝
v-copy
內容復制到剪切板中
const copy = { bind(el, { value }) { el.$value = value el.handler = () => { if (!el.$value) { // 值為空的時候,給出提示??筛鶕椖縐I仔細設計 console.log('無復制內容') return } // 動態(tài)創(chuàng)建 textarea 標簽 const textarea = document.createElement('textarea') // 將該 textarea 設為 readonly 防止 iOS 下自動喚起鍵盤,同時將 textarea 移出可視區(qū)域 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('復制成功') } document.body.removeChild(textarea) } // 綁定點擊事件 el.addEventListener('click', el.handler) }, // 當傳進來的值更新的時候觸發(fā) componentUpdated(el, { value }) { el.$value = value }, // 指令與元素解綁的時候,移除事件綁定 unbind(el) { el.removeEventListener('click', el.handler) }, } export default copy
v-longpress
實現一個用戶長按鼠標左鍵或移動端單指長按,觸發(fā)的事件
const longpress = { bind(el, binding) { if (typeof binding.value!== 'function') { throw new Error('Callback must be a function'); } let pressTimer = null; // 鼠標(左鍵)按下、移動端按下 且 按下持續(xù)時間超過 1s 時,觸發(fā) const start = (e) => { if ( (e.type === 'mousedown' && e.button!== 0) || (e.type === 'touchstart' && e.touches.length > 1) ) { return; } pressTimer = setTimeout(() => { binding.value(e); }, 1000); }; // 鼠標(左鍵)抬起、移動端抬起 或 按下時間小于 1s 時,移除定時器 const cancel = () => { if (pressTimer!== null) { clearTimeout(pressTimer); pressTimer = null; } }; // 事件監(jiān)聽 el.addEventListener('mousedown', start); el.addEventListener('touchstart', start); el.addEventListener('click', cancel); el.addEventListener('mouseout', cancel); el.addEventListener('touchend', cancel); el.addEventListener('touchcancel', cancel); }, // 指令與元素解綁的時候,移除事件綁定 unbind(el) { el.removeEventListener('mousedown', start); el.removeEventListener('touchstart', start); el.removeEventListener('click', cancel); el.removeEventListener('mouseout', cancel); el.removeEventListener('touchend', cancel); el.removeEventListener('touchcancel', cancel); }, }; export default longpress
v-waterMarker
頁面增加水印
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
到此這篇關于Vue 自定義指令的文章就介紹到這了,更多相關Vue 自定義指令內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue多頁面配置打包性能優(yōu)化方式(解決加載包太大加載慢問題)
這篇文章主要介紹了Vue多頁面配置打包性能優(yōu)化方式(解決加載包太大加載慢問題),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01vue3使用vueup/vue-quill富文本、并限制輸入字數的方法處理
這篇文章主要介紹了vue3使用vueup/vue-quill富文本、并限制輸入字數,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03