微信小程序自定义组件同步调用

目前微信官方的推荐写法一般都是用triggerEvent来抛出数据,用bind...来接收

这里提供组件的同步调用不适用bind来接收triggerEvent抛出的数据

例子:自定义弹窗,同步调用自定义弹窗组件返回当前用户操作结果

(借助了co.js,不想使用的可以用async和await代替)

组件内实现:

const regeneratorRuntime = require('/lib/co/runtime')
const co = require('/lib/co/co')
Component({
    successfun:null,
    showPopSync:co.wrap(function*(obj={}){
      let that=this
      return new Promise((resolve, reject) => {
        that.successfun= function(res) {
          resolve(res)
        }
        that.showModal(obj)
      })
    }),
    
    //这里执行数据初始化例如设置弹窗内容什么的
    showModal:co.wrap(function*(obj){
        
    }),
    
    //用户在页面内点击了确认按钮
    userConfirm:function(){
        that.successfun({
            confirm:true
        })
    },

    //用户在页面内点击了取消按钮
    userCancel:function(){
        that.successfun({
            cancel:true
        })
    },
})

调用组件页面内实现:

wxml:

<modal id="modal" />

js:

Page({
    showSelfModal:co.wrap(function*(){
        let res=yield this.selectComponent("#modal").showPopSync({
            title:"提示"
        })
        if(res.confirm){
            //用户确认弹窗内容
        }
    })
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值