目前微信官方的推荐写法一般都是用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){
//用户确认弹窗内容
}
})
})
本文介绍了微信官方推荐使用`triggerEvent`传递数据,以及如何在组件间同步调用并用`co.js`实现异步处理,通过实例展示了在自定义弹窗组件中使用`showPopSync`方法,以及在调用页面如何接收和处理用户确认与取消操作。


被折叠的 条评论
为什么被折叠?



