欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue 自定義指令詳解

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

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

為什么要自定義指令

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

指令注冊(cè)

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

全局注冊(cè)

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

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

局部注冊(cè)

在你自己組件或頁面中,使用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]的格式動(dòng)態(tài)傳遞參數(shù)。
v-myDirective:click.top.bar="clickHandle" 傳遞修飾符top和bar。

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

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

const myDirective = {
  // 在綁定元素的 attribute 前
  // 或事件監(jiān)聽器應(yīng)用前調(diào)用
  created(el, binding, vnode) {
    // 下面會(huì)介紹各個(gè)參數(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元素時(shí)調(diào)用,可以定義一個(gè)在綁定時(shí)執(zhí)行一次的初始化動(dòng)作,此時(shí)獲取父節(jié)點(diǎn)為null。
  • bind: function (el, {value:{fn,time}}) {}
  • el:指令綁定的元素、用來操作DOM
  • value:指令的綁定值inserted: 被綁定元素插入父節(jié)點(diǎn)時(shí)調(diào)用,此時(shí)可以獲取到父節(jié)點(diǎn)。
  • update: 所在組件的VNode更新時(shí)調(diào)用,但是可能發(fā)生在其子 VNode 更新之前。指令的值可能發(fā)生了改變,也可能沒有。但是你可以通過比較更新前后的值來忽略不必要的模板更新componentUpdated: 指令所在組件的 VNode 及其子 VNode 全部更新后調(diào)用。

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

常見指令的封裝

v-copy

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

const copy = {
  bind(el, { value }) {
    el.$value = value
    el.handler = () => {
      if (!el.$value) {
        // 值為空的時(shí)候,給出提示。可根據(jù)項(xiàng)目UI仔細(xì)設(shè)計(jì)
        console.log('無復(fù)制內(nèi)容')
        return
      }
      // 動(dòng)態(tài)創(chuàng)建 textarea 標(biāo)簽
      const textarea = document.createElement('textarea')
      // 將該 textarea 設(shè)為 readonly 防止 iOS 下自動(dòng)喚起鍵盤,同時(shí)將 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)來的值更新的時(shí)候觸發(fā)
  componentUpdated(el, { value }) {
    el.$value = value
  },
  // 指令與元素解綁的時(shí)候,移除事件綁定
  unbind(el) {
    el.removeEventListener('click', el.handler)
  },
}
export default copy

v-longpress

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

const longpress = {
  bind(el, binding) {
    if (typeof binding.value!== 'function') {
      throw new Error('Callback must be a function');
    }
    let pressTimer = null;
    // 鼠標(biāo)(左鍵)按下、移動(dòng)端按下 且 按下持續(xù)時(shí)間超過 1s 時(shí),觸發(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)(左鍵)抬起、移動(dòng)端抬起 或 按下時(shí)間小于 1s 時(shí),移除定時(shí)器
    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);
  },
  // 指令與元素解綁的時(shí)候,移除事件綁定
  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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • vue日歷組件的封裝方法

    vue日歷組件的封裝方法

    這篇文章主要為大家詳細(xì)介紹了vue封裝一個(gè)日歷組件的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • 詳解vue 配合vue-resource調(diào)用接口獲取數(shù)據(jù)

    詳解vue 配合vue-resource調(diào)用接口獲取數(shù)據(jù)

    本篇文章主要介紹了vue 配合vue-resource調(diào)用接口獲取數(shù)據(jù),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • vue中實(shí)現(xiàn)展示與隱藏側(cè)邊欄功能

    vue中實(shí)現(xiàn)展示與隱藏側(cè)邊欄功能

    這篇文章主要介紹了vue中實(shí)現(xiàn)展示與隱藏側(cè)邊欄功能,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • Vue3?實(shí)現(xiàn)驗(yàn)證碼倒計(jì)時(shí)功能(刷新保持狀態(tài))

    Vue3?實(shí)現(xiàn)驗(yàn)證碼倒計(jì)時(shí)功能(刷新保持狀態(tài))

    倒計(jì)時(shí)的運(yùn)用場景是需要經(jīng)常用到的,但是根據(jù)業(yè)務(wù)的不同,好比手機(jī)驗(yàn)證碼或者是郵箱驗(yàn)證碼之類的,即使用戶跳轉(zhuǎn)到其它頁面或者刷新,再次回到登錄也,驗(yàn)證碼的倒計(jì)時(shí)也得保持狀態(tài),下面通過本文給大家分享Vue3?驗(yàn)證碼倒計(jì)時(shí)功能實(shí)現(xiàn),感興趣的朋友一起看看吧
    2022-08-08
  • 在vue中阻止瀏覽器后退的實(shí)例

    在vue中阻止瀏覽器后退的實(shí)例

    今天小編就為大家分享一篇在vue中阻止瀏覽器后退的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-11-11
  • vue 項(xiàng)目常用加載器及配置詳解

    vue 項(xiàng)目常用加載器及配置詳解

    本文介紹了vue 項(xiàng)目常用加載器及配置詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-01-01
  • Vue多頁面配置打包性能優(yōu)化方式(解決加載包太大加載慢問題)

    Vue多頁面配置打包性能優(yōu)化方式(解決加載包太大加載慢問題)

    這篇文章主要介紹了Vue多頁面配置打包性能優(yōu)化方式(解決加載包太大加載慢問題),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-01-01
  • Vue3 computed初始化獲取設(shè)置值實(shí)現(xiàn)示例

    Vue3 computed初始化獲取設(shè)置值實(shí)現(xiàn)示例

    這篇文章主要為大家介紹了Vue3 computed初始化以及獲取值設(shè)置值實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-10-10
  • Vue使用Sentry實(shí)現(xiàn)錯(cuò)誤監(jiān)控

    Vue使用Sentry實(shí)現(xiàn)錯(cuò)誤監(jiān)控

    Sentry?是一款功能強(qiáng)大的開源錯(cuò)誤監(jiān)控服務(wù),廣泛用于追蹤和修復(fù)應(yīng)用中的異常情況,本文將詳細(xì)介紹如何在?Vue?應(yīng)用中集成和使用?Sentry,感興趣的可以了解下
    2024-11-11
  • vue3使用vueup/vue-quill富文本、并限制輸入字?jǐn)?shù)的方法處理

    vue3使用vueup/vue-quill富文本、并限制輸入字?jǐn)?shù)的方法處理

    這篇文章主要介紹了vue3使用vueup/vue-quill富文本、并限制輸入字?jǐn)?shù),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-03-03

最新評(píng)論