使用ts开发小程序时,拓展wx的属性或者方法

395 阅读1分钟

类型声明

declare namespace WechatMiniprogram {
  interface Wx {
    custom: {
      toast(
        text?: string,
        duration?: number,
        success?: "success" | "none"
      ): void;
    };
  }
}

方法实现

const custom = {
      toast: function(text?: string, duration?: number, success?: boolean) {
		wx.showToast({
			title: text || "出错啦~",
			icon: success ? 'success' : 'none',
			duration: duration || 2000
		})
	},
}

添加到微信实例

// 在app.ts开头添加以下代码

wx.custom = custom

使用

然后就可以在其他地方使用了 wx.custom.toast()

我很少这样用,只是有个库要把他的属性加到wx上边,所以才写了这么一篇,建议是把方法和属性写到单独的文件,使用的时候引用进来