一、使用import方法引入
- 将要重复调用的方法
// modal方法
// 使用model方法时,可以传入参数,也可以不传入参数,如果需要传入参数,要传入对象作为参数
const model=(options = {}) => {
// 在方法内部通过Promise返回用户的操作
// 如果用户点击了确定,需要通过resolve返回true;如果用户点击了取消,需要通过resolve返回false
return new Promise((resolve)=>{
const defaultOpt={
title:'提示',
content:'您确定执行该操作吗?',
confirmColor:'#f3514f'
}
// 通过Object.assign方法将参数进行合并
// 使用传入的参数覆盖默认的参数,将合并以后的参数赋值给一个空对象,从而不影响默认的参数
const opts=Object.assign({},defaultOpt,options)
wx.showModal({
// 将合并以后的参数通过展开运算符赋值给wx.showModal对象
...opts,
complete({confirm,cancel}){
confirm && resolve(true)
cancel && resolve(false)
}
})
})
}
// 如果其他js文件需要使用model方法,需要先导入model,然后进行调用即可。
export{model}
- 在app.js页面使用import方法引入
import {model} from "./utils/extendApi"
App({
async onShow(){
// 引入model不传递参数
await model()
// 引入model传递参数
await model({title:'新的提示',showCancel:false})
}
})
二、使用wx全局对象引入
- 将要重复调用的方法
const model=(options = {}) => {
// 在方法内部通过Promise返回用户的操作
// 如果用户点击了确定,需要通过resolve返回true;如果用户点击了取消,需要通过resolve返回false
return new Promise((resolve)=>{
const defaultOpt={
title:'提示',
content:'您确定执行该操作吗?',
confirmColor:'#f3514f'
}
// 通过Object.assign方法将参数进行合并
// 使用传入的参数覆盖默认的参数,将合并以后的参数赋值给一个空对象,从而不影响默认的参数
const opts=Object.assign({},defaultOpt,options)
wx.showModal({
// 将合并以后的参数通过展开运算符赋值给wx.showModal对象
...opts,
complete({confirm,cancel}){
confirm && resolve(true)
cancel && resolve(false)
}
})
})
}
// 将 model方法挂载到wx全局对象身上,避免每次使用都要进行导入。
// 如果想挂载到wx全局对象上这种写法生效,需要让当前文件执行一次。
wx.model=model
- 在app.js页面使用wx全局对象引入
import {toast} from "./utils/extendApi"
App({
onShow(){
// 使用全局方法不传入参数
// 通过Promise返回的参数,需要加await,onShow前加async
const res = await wx.model()
console.log(res)
// 使用全局方法传入参数
const res = await wx.model({
title:'新的提示',
showCancel:false
})
console.log(res)
}
})