当前位置:   article > 正文

vue3 + uniapp + ts 拓展全局类型处理_cloudio/types

cloudio/types

背景:

我们在使用uniapp + ts开发中,由于在vue3中this问题带来的全局挂在不是那么好实现,例如我们开发了一些通用工具函数,每次使用的时候都要引入很麻烦,就想到this不可用,可使用uni来挂在,uni也是一个全局对象,是对象就可以拓展,在uni上挂在新的属性或方法很容易,问题是怎么处理ts的类型检查报错和使用api提示呢?

处理:

本人在遇到此问题时,看了下网上别人的处理方式(大家可自行百度),没有一个比较简单可用,于是乎就自己搞了,顺便在此记录分享一下,万一有人也很需要呢

1. src目录下创建types文件夹,用户存放通用类型声明文件,在创建的types文件夹下创建global.d.ts类型声明文件

2.在sconfig.json文件中将声明文件包含进去

  1. {
  2. "extends": "@vue/tsconfig/tsconfig.json",
  3. "compilerOptions": {
  4. "target": "ESNext",
  5. "useDefineForClassFields": true,
  6. "module": "ESNext",
  7. "moduleResolution": "Node",
  8. "strict": true,
  9. "jsx": "preserve",
  10. "sourceMap": true,
  11. "resolveJsonModule": true,
  12. "isolatedModules": true,
  13. "esModuleInterop": true,
  14. "lib": ["ESNext", "DOM"],
  15. "skipLibCheck": true,
  16. "types": ["vite/client", "@dcloudio/types", "@uni-helper/uni-app-types", "@uni-helper/uni-cloud-types", "@uni-helper/uni-ui-types"],
  17. "strictNullChecks": true,
  18. "ignoreDeprecations": "5.0",
  19. "baseUrl": "./", // 解析非相对模块的基础地址,默认是当前目录
  20. "paths": {
  21. // 路径映射,相对于baseUrl
  22. "@/*": ["src/*"]
  23. }
  24. },
  25. "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue", "src/components/table/.vue.ts"],
  26. "references": [{ "path": "./tsconfig.node.json" }]
  27. }

3.在创建的global.d.ts里愉快的添加类型

  1. import type { Uni as _Uni } from '@dcloudio/types';
  2. declare global {
  3. /**
  4. *拓展全局变量Uni
  5. */
  6. interface Uni extends _Uni {
  7. $u: {
  8. loading(show: boolean, title?: string): void;
  9. toast(title: string): void;
  10. };
  11. }
  12. }

4.在src/utils里定义和挂载实现

 

  1. /**
  2. * 展示加载效果
  3. *
  4. * @param show 是否展示
  5. * @param title 提示信息
  6. */
  7. function loading(show: boolean, title = '加载中...') {
  8. if (show) {
  9. uni.showLoading({ title });
  10. } else {
  11. uni.hideLoading();
  12. }
  13. }
  14. /**
  15. * 展示提示消息
  16. *
  17. * @param title 提示消息
  18. */
  19. function toast(title: string) {
  20. uni.showToast({
  21. icon: 'none',
  22. title
  23. });
  24. }
  25. /**
  26. * 挂在uni简化方案
  27. */
  28. export default {
  29. install() {
  30. if (!uni || typeof uni !== 'object') return;
  31. uni.$u = {
  32. loading,
  33. toast
  34. };
  35. }
  36. };

5.实现后记得引用一下(初始化挂载)

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号