在小程序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>
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐