vue3+TS 實(shí)現(xiàn)自定義指令長按觸發(fā)綁定的函數(shù)
而然間看到一個(gè)在vue2中寫的長按觸發(fā)事件的自定義指定,想著能不能把他copy到我的vue3項(xiàng)目中呢。
編寫自定義指令時(shí)遇到的幾個(gè)難點(diǎn)
1.自定義指令的類型
在ts中寫任何東西都要考慮到類型的問題,自定義指令的類型問題依然存在
2.在ts中使用setTimeout() 函數(shù)
setTimeout()函數(shù)的默認(rèn)返回值是一個(gè)隨機(jī)的number ,這個(gè)number 代表了這個(gè)計(jì)時(shí)器的唯一id,但是并不能直接將其類型定義為number 否則會(huì)出現(xiàn)報(bào)錯(cuò)。
3.自定義指令的傳參問題
我這里的傳參方法只做參考,寫的很不規(guī)范。具體的好多傳參的方法請(qǐng)自行搜索
代碼
這個(gè)是我自己編寫的長按觸發(fā)綁定的函數(shù)
directives/longPress.ts
import { ObjectDirective } from 'vue'
const LongPress: ObjectDirective = {
// 組件mounted時(shí)執(zhí)行指令
mounted(el, binding, vNode) {
// 確保提供的表達(dá)式是函數(shù)
if (typeof binding.value !== 'function') {
// // 將警告?zhèn)鬟f給控制臺(tái)
let warn = `[longpress:] provided expression '${binding.value}' is not afunction, but has to be `
console.log(warn)
} else {
console.table({ el, binding, vNode })
let timer: ReturnType<typeof setTimeout> | null = null //定義空 定時(shí)器
const start = (e: MouseEvent | TouchEvent) => {
console.log(e)
//下列事件不執(zhí)行1.不是鼠標(biāo)左鍵2.單擊事件 (3.沒有傳入長按時(shí)間 ?? 有默認(rèn))
if ((<MouseEvent>e).button !== 0 && e.type === 'click') {
return
}
if (timer == null) {
timer = setTimeout(() => {
handler()
}, Number(binding.arg) * 1000 ?? 0.5 * 10000) //默認(rèn)長按0.5秒執(zhí)行綁定的函數(shù)
}
}
const cancel = () => {
if (timer !== null) {
clearTimeout(timer)
console.log(timer);//定時(shí)器默認(rèn)返回一個(gè)隨機(jī)的number 這個(gè)number的值是這個(gè)定時(shí)器的id
timer = null
}
}
const handler = () => {
binding.value()
}
// 添加事件監(jiān)聽器
el.addEventListener('mousedown', start)
el.addEventListener('touchstart', start)
// 取消計(jì)時(shí)器
el.addEventListener('click', cancel)
el.addEventListener('mouseout', cancel)
el.addEventListener('touchend', cancel)
el.addEventListener('touchcancel', cancel)
}
},
}
export default LongPress在main.ts中引入 作為全局自定義指令
import { createApp } from 'vue'
import App from './App.vue'
import LongPress from './directives/longpress'
const app = createApp(App)
app.directive('longPress',LongPress)
app.mount('#app')在組件中使用
這里的v-longPress 便是自定義指令,其中此處的參數(shù)傳遞方法僅供參考
<template>
<div>
<button v-longPress = 'longFunc,1' >longPress</button>
</div>
</template>
<script setup lang="ts">
const longFunc = () => {
console.log('click long btn');
alert('click long btn')
}
</script>
<style scoped>
</style>到此這篇關(guān)于vue3+TS 自定義指令:長按觸發(fā)綁定的函數(shù)的文章就介紹到這了,更多相關(guān)vue3 ts自定義指令內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
ElementUI多個(gè)子組件表單的校驗(yàn)管理實(shí)現(xiàn)
這篇文章主要介紹了ElementUI多個(gè)子組件表單實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
vue.js利用defineProperty實(shí)現(xiàn)數(shù)據(jù)的雙向綁定
本篇文章主要介紹了用Node.js當(dāng)作后臺(tái)、jQuery寫前臺(tái)AJAX代碼實(shí)現(xiàn)用戶登錄和注冊(cè)的功能的相關(guān)知識(shí)。具有很好的參考價(jià)值。下面跟著小編一起來看下吧2017-04-04
VUE父組件異步獲取數(shù)據(jù),子組件接收的值為空的問題
這篇文章主要介紹了VUE父組件異步獲取數(shù)據(jù),子組件接收的值為空的問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10

