vue3 + elementPlus 自定义指令 实现自动聚焦 自动选中 整数/小数点限制

定义指令

import { App, nextTick } from 'vue'
// 根据el获取input
const getInput = (el: HTMLElement): HTMLInputElement | null => el instanceof HTMLInputElement ? el : el.querySelector('input')
export default {
    install (app: App) {
        // v-focus 自动聚焦。对于非文本框聚焦使用 v-focus:1
        app.directive('focus', {
            mounted: async (el: HTMLElement, { arg }) => {
                // 为了防止数据未即使更新。
                await nextTick()
                // 对于非文本框聚焦(使用了 contenteditable )的直接聚焦即可
                if (arg) el.focus?.()
                else getInput(el)?.focus()
            }
        })

        // v-select 自动选中。对于非文本框请使用 v-select:1
        app.directive('select', {
            mounted: async (el: HTMLElement, { arg }) => {
                // 为了防止数据未即使更新。
                await nextTick()
                if (arg) el
                // elementplus的文本框。是嵌套了一个文本框。。
                getInput(el)?.select()
            }
        })

        let inputHandler = () => {}
        // 限制input框,仅能输入数字。默认限制输入整数,可以通过传参设置小数位数
        // v-number 限制整数,v-number:2 限制两位小数,v-number:2=3 限制两位小数,整数位三位,v-number=2 限制两位整数\
        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>

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值