亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Vue 自定義指令詳解

 更新時間:2025年01月03日 09:34:25   作者:北巷`  
本文介紹了如何在Vue中定義和使用自定義指令,包括指令的注冊、鉤子函數(shù)、參數(shù)以及常見指令的封裝,如v-copy、v-longpress等,自定義指令在處理某些底層DOM操作時非常便捷,感興趣的朋友一起看看吧

首先,我們知道vue中有很多自帶指令,v-bind、v-on、v-model等。但在業(yè)務(wù)開發(fā)中,我們常見一些自定義指令如:v-copy、v-longpress等。那么如何定義自己所需的指令呢?
接下來我們分別從指令注冊、指令的鉤子函數(shù)、指令的參數(shù)以及常見指令的封裝進(jìn)行介紹

為什么要自定義指令

在使用vue的時候 我們某些場景下仍然需要對普通 DOM 元素進(jìn)行底層操作,
在vue中、組件渲染需要時間,獲取DOM常需要搭配setTimeout、$nextTick使用
而自定義指令在使用時,更便捷。

指令注冊

指令的注冊命令:Vue.directive(key, directives[key])
使用:Vue.use()

全局注冊

在我們常見的項(xiàng)目結(jié)構(gòu)中、directives文件夾下,定義的index.js文件中,我們會對指令進(jìn)行全局注冊。

import MyDirective from './directive/myDirective' 
const directives = { 
  MyDirective 
}
export default { 
  install(app) {
    // 遍歷、注冊
   Object.keys(directives).forEach((key) => {    
    app.directive(key, directives[key])  
   })
  }
}

局部注冊

在你自己組件或頁面中,使用directives選項(xiàng)自定義指令

export default {
  directives: {
    myDirective: {
      inserted: function (el) {
        //
      }
    }
  }
}

使用

<input v-myDirective>

添加參數(shù)
v-myDirective="data" 傳遞數(shù)值給指令,這里的data可以是組件中的data數(shù)據(jù),也可以是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",傳遞參數(shù)click,這里可以通過[xx]的格式動態(tài)傳遞參數(shù)。
v-myDirective:click.top.bar="clickHandle" 傳遞修飾符top和bar。

注意:不推薦在組件上使用自定義指令、它會應(yīng)用于組件的根結(jié)點(diǎn)、和透傳 attributes 類似。

指令的鉤子和參數(shù)

const myDirective = {
  // 在綁定元素的 attribute 前
  // 或事件監(jiān)聽器應(yīng)用前調(diào)用
  created(el, binding, vnode) {
    // 下面會介紹各個參數(shù)的細(xì)節(jié)
  },
  // 在元素被插入到 DOM 前調(diào)用
  beforeMount(el, binding, vnode) {},
  // 在綁定元素的父組件
  // 及他自己的所有子節(jié)點(diǎn)都掛載完成后調(diào)用
  mounted(el, binding, vnode) {},
  // 綁定元素的父組件更新前調(diào)用
  beforeUpdate(el, binding, vnode, prevVnode) {},
  // 在綁定元素的父組件
  // 及他自己的所有子節(jié)點(diǎn)都更新后調(diào)用
  updated(el, binding, vnode, prevVnode) {},
  // 綁定元素的父組件卸載前調(diào)用
  beforeUnmount(el, binding, vnode) {},
  // 綁定元素的父組件卸載后調(diào)用
  unmounted(el, binding, vnode) {}
}
  • bind: 只調(diào)用一次,指令第一次綁定到HTML元素時調(diào)用,可以定義一個在綁定時執(zhí)行一次的初始化動作,此時獲取父節(jié)點(diǎn)為null。
  • bind: function (el, {value:{fn,time}}) {}
  • el:指令綁定的元素、用來操作DOM
  • value:指令的綁定值inserted: 被綁定元素插入父節(jié)點(diǎn)時調(diào)用,此時可以獲取到父節(jié)點(diǎn)。
  • update: 所在組件的VNode更新時調(diào)用,但是可能發(fā)生在其子 VNode 更新之前。指令的值可能發(fā)生了改變,也可能沒有。但是你可以通過比較更新前后的值來忽略不必要的模板更新componentUpdated: 指令所在組件的 VNode 及其子 VNode 全部更新后調(diào)用。

unbind: 只調(diào)用一次, 指令與元素解綁時調(diào)用。

常見指令的封裝

v-copy

內(nèi)容復(fù)制到剪切板中

const copy = {
  bind(el, { value }) {
    el.$value = value
    el.handler = () => {
      if (!el.$value) {
        // 值為空的時候,給出提示??筛鶕?jù)項(xiàng)目UI仔細(xì)設(shè)計(jì)
        console.log('無復(fù)制內(nèi)容')
        return
      }
      // 動態(tài)創(chuàng)建 textarea 標(biāo)簽
      const textarea = document.createElement('textarea')
      // 將該 textarea 設(shè)為 readonly 防止 iOS 下自動喚起鍵盤,同時將 textarea 移出可視區(qū)域
      textarea.readOnly = 'readonly'
      textarea.style.position = 'absolute'
      textarea.style.left = '-9999px'
      // 將要 copy 的值賦給 textarea 標(biāo)簽的 value 屬性
      textarea.value = el.$value
      // 將 textarea 插入到 body 中
      document.body.appendChild(textarea)
      // 選中值并復(fù)制
      textarea.select()
      const result = document.execCommand('Copy')
      if (result) {
        console.log('復(fù)制成功') 
      }
      document.body.removeChild(textarea)
    }
    // 綁定點(diǎn)擊事件
    el.addEventListener('click', el.handler)
  },
  // 當(dāng)傳進(jìn)來的值更新的時候觸發(fā)
  componentUpdated(el, { value }) {
    el.$value = value
  },
  // 指令與元素解綁的時候,移除事件綁定
  unbind(el) {
    el.removeEventListener('click', el.handler)
  },
}
export default copy

v-longpress

實(shí)現(xiàn)一個用戶長按鼠標(biāo)左鍵或移動端單指長按,觸發(fā)的事件

const longpress = {
  bind(el, binding) {
    if (typeof binding.value!== 'function') {
      throw new Error('Callback must be a function');
    }
    let pressTimer = null;
    // 鼠標(biāo)(左鍵)按下、移動端按下 且 按下持續(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);
    };
    // 鼠標(biāo)(左鍵)抬起、移動端抬起 或 按下時間小于 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

到此這篇關(guān)于Vue 自定義指令的文章就介紹到這了,更多相關(guān)Vue 自定義指令內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論