wepy 在 methods 中调用 methods 方法,并保证 this 一致

使用 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' + '事件名' + '方法名'

	这样做比较清晰


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值