在vue项目中有computed和watch,但是微信小程序没有这两者,实际项目中小程序里面也有这样的需求,就可以使用微信小程序的wxs语法实现该功能。
场景:编辑页面用户输入市场价和优惠价,自动计算出优惠额
- wxml
<wxs module="m1">
var computeDiscountPrice = function(num1,num2) {
if(num1 && num2 && (num2 >= num1)){
return Math.round((num2-num1) * 100) / 100
}}
module.exports.computeDiscountPrice = computeDiscountPrice;
</wxs>
<!--调用并传参-->
<view>{{ m1.computeDiscountPrice(discountPrice,marketPrice) }} </view>- js
Page({
data: {
marketPrice: 200,
discountPrice:100
}
})- 页面最终渲染结果
100