mirror of
https://github.com/tenrok/maska.git
synced 2026-06-08 17:22:27 +03:00
Optimize directive work
This commit is contained in:
+16
-4
@@ -7,13 +7,18 @@ const masks = new WeakMap<HTMLInputElement, MaskInput>()
|
||||
|
||||
export const vMaska: MaskaDirective = (el, binding) => {
|
||||
const input = el instanceof HTMLInputElement ? el : el.querySelector('input')
|
||||
const opts = { ...(binding.arg as MaskInputOptions) } ?? {}
|
||||
|
||||
if (input == null) return
|
||||
|
||||
if (masks.get(input) != null) {
|
||||
masks.get(input)?.destroy()
|
||||
}
|
||||
const existed = masks.get(input)
|
||||
if (existed != null) {
|
||||
if (!existed.needUpdate(input, opts)) {
|
||||
return
|
||||
}
|
||||
|
||||
const opts = { ...(binding.arg as MaskInputOptions) } ?? {}
|
||||
existed.destroy()
|
||||
}
|
||||
|
||||
if (binding.value != null) {
|
||||
const binded = binding.value
|
||||
@@ -32,4 +37,11 @@ export const vMaska: MaskaDirective = (el, binding) => {
|
||||
}
|
||||
|
||||
masks.set(input, new MaskInput(input, opts))
|
||||
|
||||
// check initial value for v-model
|
||||
setTimeout(() => {
|
||||
if (input.value !== '') {
|
||||
input.dispatchEvent(new InputEvent('input'))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+21
-4
@@ -22,12 +22,16 @@ export class MaskInput {
|
||||
target: string | NodeListOf<HTMLInputElement> | HTMLInputElement,
|
||||
readonly options: MaskInputOptions = {}
|
||||
) {
|
||||
const { onMaska, preProcess, postProcess, ...opts } = options
|
||||
|
||||
if (typeof target === 'string') {
|
||||
this.init(Array.from(document.querySelectorAll(target)), opts)
|
||||
this.init(
|
||||
Array.from(document.querySelectorAll(target)),
|
||||
this.getMaskOpts(options)
|
||||
)
|
||||
} else {
|
||||
this.init('length' in target ? Array.from(target) : [target], opts)
|
||||
this.init(
|
||||
'length' in target ? Array.from(target) : [target],
|
||||
this.getMaskOpts(options)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,6 +43,19 @@ export class MaskInput {
|
||||
this.items.clear()
|
||||
}
|
||||
|
||||
needUpdate (input: HTMLInputElement, opts: MaskInputOptions): boolean {
|
||||
const mask = this.items.get(input) as Mask
|
||||
const maskNew = new Mask(parseInput(input, this.getMaskOpts(opts)))
|
||||
|
||||
return JSON.stringify(mask.opts) !== JSON.stringify(maskNew.opts)
|
||||
}
|
||||
|
||||
private getMaskOpts (options: MaskInputOptions): MaskOptions {
|
||||
const { onMaska, preProcess, postProcess, ...opts } = options
|
||||
|
||||
return opts
|
||||
}
|
||||
|
||||
private init (inputs: HTMLInputElement[], defaults: MaskOptions): void {
|
||||
for (const input of inputs) {
|
||||
const mask = new Mask(parseInput(input, defaults))
|
||||
|
||||
Reference in New Issue
Block a user