现在ts+scss开发小程序越来越多了,我们平时调用showModal弹窗相对频繁的话,可以对它进行封装,减少代码量,方便调用。
我们先看正常的展示效果

再看微信小程序的原调用代码
- wx.showModal({
- title: '提示',
- content: '是否确认的提示内容',
- success (res) {
- if (res.confirm) {
- console.log('用户点击确定')
- } else if (res.cancel) {
- console.log('用户点击取消')
- }
- }
- })
提炼可以成为变量的部分,一般情况是三个,有取消操作的话,是4个。
1.title:弹窗提示标题,一般默认“提示”
2. content:弹窗提示标题,一般根据自己业务情况提示
3.res.confirm:点确定后执行的任务
4.res.cancel:点取消后执行的任务
确认我们需要作为调用的4个元素后,我们接下来进行封装
首先,找到utils/utils.ts文件,这里面一般写需要调用的公共方法

然后在utils.ts文件里完整封装代码
只有确认操作的可以用此代码,平时也是用得最多的
- const showModal = (title:string='提示',content:string,confirmBack= () => {}) => {
- return wx.showModal({
- title,
- content,
- success (res):any{
- if (res.confirm) {
- confirmBack()
- } else if (res.cancel) {
- console.log('用户点击取消')
- }
- }
- })
- }
- export{
- showModal
- }
取消操作后需要触发时间的可以用此代码
- const showModal = (title:string='提示',content:string,confirmBack= () => {},cancelBack= () => {}) => {
- return wx.showModal({
- title,
- content,
- success (res):any{
- if (res.confirm) {
- confirmBack()
- } else if (res.cancel) {
- cancelBack()
- }
- }
- })
- }
- export{
- showModal
- }
先找到需要调用的ts文件地址,然后引入该调用方法
ts顶部引入utils文件方法
import { showModal} from "../../../utils/util"
在需要的地方使用 showModal
- //发起退款
- refund(){
- showModal(undefined,"是否确认退款",function() {
- console.log('确认退款')
- })
- },
注意,我这里的第一个参数使用undefined,他会默认填充封装方法里的初始值“提示”。
最后看调用成功后的结果
展示效果
确认后输出结果

以上就是成功后的结果显示,大家也可以在里面执行方法,跳转链接等等