如何在小程序的wxml中书写函数逻辑,wxs的使用

在小程序wxml的页面中我们可以使用{{}}内部来书写简单的js表达式,如三目运算符等,但是对于稍微复杂一点的逻辑我们就需要用函数来解决,如果写在js文件中有些繁琐还需要绑定数据等,此时wxs就配上了用场  wxs只支持ES5!!!

1、案例说明:

我们将实现下图的价格部分的逻辑,前端返回对现象内有两个属性price和discount_price,当折扣价为null时,只显示原价,当折扣价不为空时显示折扣价且将原价画一个线。

分文件编写:

1、创建一个后缀名是wxs的文件,书写函数逻辑:

// 如果不进行函数处理,当只有一个原价时,它会将原价也打上删除线,所以必须用该逻辑实现

// 最终要显示的价格
function showPrice(price, discountPrice) {
    if (!discountPrice) {
        return {
            price: price,
            display: true
        }
    } else {
        return {
            price: discountPrice,
            display: true
        }
    }
}

// 显示有切割线的那个价格
function cutPrice(price, discountPrice) {
    if (discountPrice) {
        return {
            price: price,
            display: true
        }
    } else {
        return {
            price: '',
            display: false
        }
    }
}
// 导出这两个函数
module.exports = {
    showPrice: showPrice,
    cutPrice: cutPrice
}

2、将其引入到wxml中:

module相当于之后要操作的对象

<!-- 导入wxs逻辑 -->
<wxs src="../../wxs/price.wxs" module="p"></wxs>

3、在对应的标签中使用:

<l-price 
    value="{{p.showPrice(data.price,data.discount_price).price}}">
</l-price>
<l-price  
    wx:if="{{p.cutPrice(data.price,data.discount_price).display}}" 
    deleted 
    value="{{p.cutPrice(data.price,data.discount_price).price}}">
</l-price>

直接在wxml下写:

类似于html的<script>写在下面:

<l-price 
    value="{{p.showPrice(data.price,data.discount_price).price}}">
</l-price>
<l-price  
    wx:if="{{p.cutPrice(data.price,data.discount_price).display}}" 
    deleted 
    value="{{p.cutPrice(data.price,data.discount_price).price}}">
</l-price>

<wxs module="p">
// 如果不进行函数处理,当只有一个原价时,它会将原价也打上删除线,所以必须用该逻辑实现

// 最终要显示的价格
function showPrice(price, discountPrice) {
    if (!discountPrice) {
        return {
            price: price,
            display: true
        }
    } else {
        return {
            price: discountPrice,
            display: true
        }
    }
}

// 显示有切割线的那个价格
function cutPrice(price, discountPrice) {
    if (discountPrice) {
        return {
            price: price,
            display: true
        }
    } else {
        return {
            price: '',
            display: false
        }
    }
}
// 导出这两个函数
module.exports = {
    showPrice: showPrice,
    cutPrice: cutPrice
}
</wxs>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值