1.首先在src目录下面新建一个types声明类型的文件夹,再新建一个global.d.ts文件,如图
2.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(msg: string): void;
testGloable(params:any) :void;
};
$tools:{
toast(msg: string): void;
}
}
}
3.在tsconfig.json文件添加 .d.ts后缀的类型,一般自带的都有
4.新建一个utils文件
5.utils.ts代码
function toast(msg: string) {
uni.showToast({
title: msg,
duration: 2000,
mask: false,
icon: 'none',
})
}
function testGloable(params?:any) {
console.log("我是全局方法",params)
}
export default {
install() {
// 注册全局方法
if(!uni || typeof uni !== 'object'){
return
}
uni.$u = {
toast,
testGloable
}
uni.$tools = {
toast
}
}
}
注意:新添加全局的方法时,要在声明文件里面一起添加
6.最后在main.ts里面引入
import utils from "@/common/utils/utils";
app.use(utils); // 注册全局方法
7.在页面直接使用
uni.$u.toast('请求成功')
uni.$tools.toast('请求成功')