小程序有没有类似vue或者mobx提供的计算属性?
发布于 5 年前 作者 wei38 6164 次浏览 来自 问答

小程序有没有类似vue或者mobx提供的计算属性?

比如登录的这个业务场景:

  1. 需要输入账户,且账户位数是11位

  2. 需要输入验证码,且验证码位数是4位

此时,登录的按钮才可以点击。

目前小程序里面实现是这样的:

Page({
   data: {
       phoneValue: '',
       verifyCodeValue: '',
       canLogin: false,
   },
   bindPhoneInput: function (e) {
       const phoneValue = e.detail.value;
       this.setData({ phoneValue, canLogin: false });
       const { verifyCodeValue } = this.data;
       if (phoneValue && verifyCodeValue && phoneValue.length == 11 && verifyCodeValue.length == 4) {
           this.setData({ canLogin: true });
       }
   },
   bindVerifyCodeInput: function (e) {
       const verifyCodeValue = e.detail.value;
       this.setData({ verifyCodeValue, canLogin: false })
       const { phoneValue } = this.data;
       if (phoneValue && verifyCodeValue && phoneValue.length == 11 && verifyCodeValue.length == 4) {
           this.setData({ canLogin: true });
       }
   }
})

这样的代价是需要在需要组合属性判断的地方,全部都维护一次canLogin来渲染页面,组合属性越多的话,代码维护就越麻烦,且非常不优雅。

有没有类似vue里面的computed,或者是mobx里面的computed这种计算属性的方式来应对这种业务需求呢?

4 回复

mobx-miniprogram 这个库能用吗?要是能用能否提供个简单的demo

你好,你的反馈我们已收到,我们会在后续的版本中考虑增加类似功能。

回到顶部