import { PluginObject } from 'vue' import { filterMessage } from '../filters' declare var Promise: any export interface IOptions { // 排除那些不需要弹窗提示的文案 exclude: string [], // 弹窗提示 toast(message: string): any, } export const defaultOptions: IOptions = { exclude: ['', 'cancel'], toast: (message) => console.log(message), } const Es6Promise: PluginObject = { install(Vue, options) { this.setDefaultOptions(options) Promise.prototype.toast = function (callback: { [prop: string]: any } | ((err: any, message: string) => any)) { return this.catch(err => { const message = filterMessage(err) // 如果给的是对象,直接对象上赋值 不再提示了 if (typeof callback === 'object') { callback.superError = message return } // 如果传参是函数那么默认就不再弹窗弱提示了 if (typeof callback === 'function' && !callback(err, message)) return const { exclude, toast } = defaultOptions if (!exclude.includes(message)) { // 弱提示 toast(message) } }) } Promise.prototype.success = function (options: string | boolean) { return this.then(res => { let message = filterMessage(res) const { exclude, toast } = defaultOptions if (typeof options === 'string') { message = options } else if (options === false) { return } if (!exclude.includes(message)) { // 弱提示 toast(message) } }) } Promise.prototype.null = function () { return this.catch(err => console.log(err)) } Promise.prototype.finally = function (callback: () => any) { const P = this.constructor return this.then( value => P.resolve(callback()).then(() => value), reason => P.resolve(callback()).then(() => { throw reason }) ) } }, // 设置默认配置 setDefaultOptions (options?: IOptions) { Object.assign(defaultOptions, options) }, } export default Es6Promise