使用 wepy 开发微信小程序时,可能会出现以下情况:
export default class AccountForgetPassword extends wepy.page {
config = {
}
data = {
}
methods = {
// 获取图形验证码
getCaptchaCode () {
},
// 发送短信验证码
sendVerificationCode () {
// 当短信验证码,验证过期等其他情况时,我们需要重新获取 '图形验证码'
// 我们想着直接调用 'getCaptchaCode()'
this.methods.getCaptchaCode()
/*
但是,这样调用,getCaptchaCode() 的 this 作用域并非外层的 this
*/
}
}
}
下面是解决方法:
export default class AccountForgetPassword extends wepy.page {
config = {
}
// 将获取图形验证码的方法,定义到外层
getCaptchaCode () {
}
data = {
}
methods = {
// 获取图形验证码
onTapGetCaptchaCode () {
this.getCaptchaCode()
},
// 发送短信验证码
onTapSendVerificationCode () {
// 这里也调用外层的 getCaptchaCode()
this.getCaptchaCode()
}
}
}
同时,注意下:
wepy 规定的是 methods 只负责响应页面事件,不被其它方法调用。所以,我们以后约定,methods 方法的定义为:
'on' + '事件名' + '方法名'
这样做比较清晰