Vue3+TS自定义指令系列-限制输入(v-input)

1,073 阅读1分钟

需求:限制输入框只能输入金额或正整数

思路;直接通过指令传入需要限定的类型,限定输入的内容

实现:通过获取input元素,监听其输入行为,通过正则表达式替换不合法的输入内容,再重新赋值输入框的value值

使用:通过v-input.money或v-input.int使用,目前暂时只有此两种限制

主要实现代码:

import type { Directive, DirectiveBinding } from 'vue';

/**
 *
 * @param el
 * @param binding
 * v-input.money 限制输入金额
 * v-input.int 限制输入整数
 * 可用于 input 或 el-input等输入框组件
 */

const vInput: Directive = (el: HTMLElement, binding: DirectiveBinding) => {
    let inp: HTMLInputElement;
    if (el.tagName.toLowerCase() == 'input') {
        inp = el as HTMLInputElement;
    } else {
        inp = el.querySelector('input') as HTMLInputElement;
    }
    // 金额限制
    function limitMoney(value: string) {
        return value
            .replace(/[^\d.]/g, '')
            .replace(/\.{2,}/g, '.')
            .replace(/^0+/g, '0')
            .replace(/^0+\./g, '0.')
            .replace(/^0+\d/g, '0')
            .replace(/^(\d+)\.(\d\d).*$/, '$1.$2');
    }
    // 整数限制
    function limitInteger(value: string) {
        return value.replace(/[^\d]/g, '').replace(/^0+/g, '0').replace(/^0+\d/g, '0');
    }
    inp.addEventListener('input', () => {
        // 金额限制
        if (binding.modifiers.money) return (inp.value = limitMoney(inp.value.toString()));
        // 整数限制
        if (binding.modifiers.int) return (inp.value = limitInteger(inp.value.toString()));
    });
};
export default vInput;

全局组件注册

// 在 directives目录下 建立index.ts文件
import type { App, Directive } from 'vue';
import input from './vInput';

interface Directives {
    input: Directive;
}

// 注意:使用时需要(v-)开头
const directives: Directives = { input };

export default {
    install(app: App) {
        Object.keys(directives).forEach(key => {
            app.directive(key, directives[key as keyof Directives]);
        });
    },
};


// 在main.ts中的操作如下
import { createApp } from 'vue';
import App from './App.vue';
import directives from './directives/index';

const app = createApp(App);
app.use(directives);

使用示例:

<template>
    <el-input v-input.int v-model="text"></el-input>
    <input v-input.money v-model="money" />
</template>

<script setup lang="ts">
    import { ref } from 'vue';
    let text = ref(0);
    let money = ref(0)
</script>

如遇到问题可在评论区留言