小程序中当我们需要去使用某些自定义组件时,会使用这种方式,
在组件上定义方法,等组件内功能执行完成后,使用triggerEvent去触发对应的父组件/父页面相关方法。
<!-- pages/index/index.wxml -->
<custom-modal id="customModal" bind:confirm='confirm' bind:cancel='cancel'></custom-modal>
// pages/index/index.js
Page({
data: {
},
confirm() {
// 组件调用成功
},
cancel() {
// 组件调用失败
}
})
// components/index/index.js
Component({
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
cancel() {
// do something
this.triggerEvent('cancel', {})
},
confirm() {
// do something
this.triggerEvent('confirm', {})
},
}
})
但是这种方法需要在页面内重复定义一些方法,如果多个页面都需要使用时很不方便。
因此我采用了另一种写法来让组件的调用方式更加的符合使用方式,最后将会实现如下效果
let component = this.selectComponent('#customComponent')
component.$$showComponent({
// 传入组件的数据
data: {
},
// 组件成功
success (res) {
console.log('组件确认', res)
},
// 组件失败
fail (err) {
console.log('用户关闭', err)
}
})
可以类似与wx.chooseImage一般的调用组件
具体的实现方式其实就是为这个组件创建一个$$showComponent方法,并且解析他的传入对象。
并且在组件的showComponent方法中处理额外的data参数
在成功/失败后,调用对应的方法
为了方便多个组件可以使用这部分统一为一个单独的behavior文件
// componentCallback.js
const voidFunction = () => {}
module.exports = Behavior({
data: {
componentSuccess: voidFunction,
componentFail: voidFunction,
componentComplete: voidFunction
},
lifetimes: {
attached() {
// console.log('behavior attached');
},
detached() {
// console.log('behavior detached');
}
},
methods: {
$$showComponent(options = {}) {
let {
success,
fail,
complete,
...otherOptions
} = options
this.setData({
showComponent: true,
componentSuccess: success || voidFunction,
componentFail: fail || voidFunction,
componentComplete: complete || voidFunction
})
let keys = Object.keys(otherOptions)
if (keys.length == 1 && keys[0] == 'data') {
otherOptions = otherOptions.data
}
this.showComponent(otherOptions)
},
$$success(e) {
this.data.componentSuccess(e)
},
$$fail(e) {
this.data.componentFail(e)
},
$$complete(e) {
this.data.componentComplete(e)
}
}
})
然后在对应的组件上添加
// 自定义组件
const componentCallback = require('../../js/componentCallback')
Component({
behaviors: [componentCallback],
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
showComponent: false, // 显示当前自定义组件
},
/**
* 组件的方法列表
*/
methods: {
showComponent(data = {}) {
console.log('通过data传入的参数', data)
// 处理传入的额外参数
},
cancel() {
let {
componentFail
} = this.data
this.setData({
showComponent: false
})
// 触发失败后的方法
componentFail()
},
confirm() {
let {
componentSuccess
} = this.data
// do something
this.setData({
showComponent: false
})
// 触发成功后的方法
componentSuccess(data)
}
}
})
如此便可以实现方法式的调用组件功能了
给自定义组件添加success和fail方法,避免在页面中额外给组件添加监听回调方法
以下是一个示例(组件内输入并在页面内显示)
代码片段:https://developers.weixin.qq.com/s/6tYPT1ml71NB