当前位置: 首页 > news >正文

实现 vue3 正整数输入框组件

1.实现代码

components/InputInteger.vue

<!-- 正整数输入框 -->
<template><el-input v-model="_value" @input="onInput" maxlength="9" clearable />
</template><script lang="ts" setup>
import { ref } from "vue";const props = withDefaults(defineProps<{modelValue?: number | string;min?: number;max?: number;}>(),{min: 1}
);
const emit = defineEmits(["update:modelValue"]);const _value = ref(props.modelValue);const onInput = (val: string | undefined) => {const result = verifyValue(val); // 拦截输入,进行校验_value.value = result;emit("update:modelValue", result);
};const verifyValue = (value: string | undefined): number | string | undefined => {const { max, min } = props;let result = value;let newVal = Number(value);if (isNil(value) || Number.isNaN(newVal) || hasDot(value)) {return props.modelValue; // 保持输入前的数值}if (value === "") {return undefined;}if (max && newVal > max) {result = String(max);}if (min && newVal < min) {result = String(min);}return result;
};// 判断null或undefined
const isNil = (value: any) => {return value == null;
};// 判断是否包含.字符
const hasDot = (value: any) => {return String(value).includes(".");
};
</script>

2.全局引入

main.ts

const app = createApp(App);app.config.errorHandler = errorHandler;// register the global component
app.component("InputInteger", InputInteger);

3.TS类型声明

src/typings/global-components.d.ts

/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// Read more: https://github.com/vuejs/core/pull/3399
export {};declare module "vue" {export interface GlobalComponents {InputInteger: (typeof import("../components/InputInteger.vue"))["default"];}
}

4. 配置 JSX/TSX 类型推断

参考:https://cn.vuejs.org/guide/extras/render-function.html#jsx-type-inference

tsconfig.json

{"compilerOptions": {"jsx": "preserve","jsxImportSource": "vue" // 指定了 TypeScript 编译 JSX 时应该从哪个库(vue/react)导入 JSX 工厂函数// ...}
}
http://www.lryc.cn/news/495289.html

相关文章:

  • Leetcode - 周赛425
  • c++(斗罗大陆2)
  • redis常见数据类型
  • MySQL - 性能优化
  • Linux进程概念-详细版(一)
  • K8S网络系列--Flannel网络下UDP、VXLAN模式的通信流程机制分析
  • ThreadLocal的设计思考
  • shell脚本练习(2)
  • 通讯专题4.1——CAN通信之计算机网络与现场总线
  • Harmony NEXT-越过相机读写权限上传图片至项目云存储中
  • MATLAB基础应用精讲-【数模应用】Retinex图像去雾算法(附MATLAB和python代码实现)
  • 点击A组件跳转到B页面的tab的某一列
  • HarmonyOS xml转换JavaScript 常用的几个方法
  • Linux笔记---进程:进程等待
  • 【Linux】匿名管道通信场景——进程池
  • 算法妙妙屋-------1.递归的深邃回响:全排列的奇妙组合
  • 【maven-6】Maven 生命周期相关命令演示
  • 黑马程序员Java笔记整理(day06)
  • LeetCode【代码随想录】刷题(动态规划篇)
  • 【看海的算法日记✨优选篇✨】第三回:二分之妙,寻径中道
  • 基于yolov8、yolov5的铝材缺陷检测识别系统(含UI界面、训练好的模型、Python代码、数据集)
  • 计算机光电成像理论基础
  • 【QNX+Android虚拟化方案】125 - 如何创建android-spare镜像
  • 深度学习基础小结_项目实战:手机价格预测
  • EMall实践DDD模拟电商系统总结
  • 【随笔】AI技术在电商中的应用
  • 序列式容器详细攻略(vector、list)C++
  • 快速启动项目
  • springboot347基于web的铁路订票管理系统(论文+源码)_kaic
  • 使用API管理Dynadot域名,在账户中添加域名服务器(Name Server)