赞
踩
背景:
我们在使用uniapp + ts开发中,由于在vue3中this问题带来的全局挂在不是那么好实现,例如我们开发了一些通用工具函数,每次使用的时候都要引入很麻烦,就想到this不可用,可使用uni来挂在,uni也是一个全局对象,是对象就可以拓展,在uni上挂在新的属性或方法很容易,问题是怎么处理ts的类型检查报错和使用api提示呢?
处理:
本人在遇到此问题时,看了下网上别人的处理方式(大家可自行百度),没有一个比较简单可用,于是乎就自己搞了,顺便在此记录分享一下,万一有人也很需要呢
1. src目录下创建types文件夹,用户存放通用类型声明文件,在创建的types文件夹下创建global.d.ts类型声明文件
2.在sconfig.json文件中将声明文件包含进去
- {
- "extends": "@vue/tsconfig/tsconfig.json",
- "compilerOptions": {
- "target": "ESNext",
- "useDefineForClassFields": true,
- "module": "ESNext",
- "moduleResolution": "Node",
- "strict": true,
- "jsx": "preserve",
- "sourceMap": true,
- "resolveJsonModule": true,
- "isolatedModules": true,
- "esModuleInterop": true,
- "lib": ["ESNext", "DOM"],
- "skipLibCheck": true,
- "types": ["vite/client", "@dcloudio/types", "@uni-helper/uni-app-types", "@uni-helper/uni-cloud-types", "@uni-helper/uni-ui-types"],
- "strictNullChecks": true,
- "ignoreDeprecations": "5.0",
-
-
- "baseUrl": "./", // 解析非相对模块的基础地址,默认是当前目录
- "paths": {
- // 路径映射,相对于baseUrl
- "@/*": ["src/*"]
- }
- },
-
- "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue", "src/components/table/.vue.ts"],
- "references": [{ "path": "./tsconfig.node.json" }]
- }

3.在创建的global.d.ts里愉快的添加类型
- import type { Uni as _Uni } from '@dcloudio/types';
-
- declare global {
- /**
- *拓展全局变量Uni
- */
- interface Uni extends _Uni {
- $u: {
- loading(show: boolean, title?: string): void;
- toast(title: string): void;
- };
- }
- }
4.在src/utils里定义和挂载实现
- /**
- * 展示加载效果
- *
- * @param show 是否展示
- * @param title 提示信息
- */
- function loading(show: boolean, title = '加载中...') {
- if (show) {
- uni.showLoading({ title });
- } else {
- uni.hideLoading();
- }
- }
-
- /**
- * 展示提示消息
- *
- * @param title 提示消息
- */
- function toast(title: string) {
- uni.showToast({
- icon: 'none',
- title
- });
- }
-
- /**
- * 挂在uni简化方案
- */
- export default {
- install() {
- if (!uni || typeof uni !== 'object') return;
- uni.$u = {
- loading,
- toast
- };
- }
- };

5.实现后记得引用一下(初始化挂载)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。