定义指令
import {
App, nextTick } from 'vue'
const getInput = (el: HTMLElement): HTMLInputElement | null => el instanceof HTMLInputElement ? el : el.querySelector('input')
export default {
install (app: App) {
app.directive('focus', {
mounted: async (el: HTMLElement, {
arg }) => {
await nextTick()
if (arg) el.focus?.()
else getInput(el)?.focus()
}
})
app.directive('select', {
mounted: async (el: HTMLElement, {
arg }) => {
await nextTick()
if (arg) el
getInput(el)?.select()
}
})
let inputHandler = () => {
}
app.directive('number', {
mounted (el: HTMLElement, {
arg, value }) {
const input: HTMLInputElement = <HTMLInputElement>getInput(el)
if (input) {
const decimal: string = arg ? `(\\.\\d{0,${
arg}})?` : ''
const integer: string = value ? `(0|[1-9]\\d{0, ${
value - 1}})` : '\\d*'
const regExp: RegExp = new RegExp((integer + decimal), 'g')
inputHandler = () => {
input.value = input.value.toString().trim().replace(/[^\d.]/g, '')?.match?.(regExp)?.[0] ?? ''
}
input.addEventListener('input', inputHandler, true)
}
},
unmounted (el: HTMLElement) {
const input: HTMLInputElement = <HTMLInputElement>getInput(el)
input.removeEventListener('input', inputHandler, true)
}
})
}
}
挂载指令
import AppVue from './App.vue'
import GlobDirective from './directive/index'
const app: App<Element> = createApp(AppVue)
app.use(GlobDirective)
使用
<template>
<input v-focus v-select v-number></input>
</template>