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


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

    1、案例说明:

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

    分文件编写:

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

    1. // 如果不进行函数处理,当只有一个原价时,它会将原价也打上删除线,所以必须用该逻辑实现
    2. // 最终要显示的价格
    3. function showPrice(price, discountPrice) {
    4. if (!discountPrice) {
    5. return {
    6. price: price,
    7. display: true
    8. }
    9. } else {
    10. return {
    11. price: discountPrice,
    12. display: true
    13. }
    14. }
    15. }
    16. // 显示有切割线的那个价格
    17. function cutPrice(price, discountPrice) {
    18. if (discountPrice) {
    19. return {
    20. price: price,
    21. display: true
    22. }
    23. } else {
    24. return {
    25. price: '',
    26. display: false
    27. }
    28. }
    29. }
    30. // 导出这两个函数
    31. module.exports = {
    32. showPrice: showPrice,
    33. cutPrice: cutPrice
    34. }

    2、将其引入到wxml中:

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

    1. <wxs src="../../wxs/price.wxs" module="p">wxs>

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

    1. <l-price
    2. value="{{p.showPrice(data.price,data.discount_price).price}}">
    3. l-price>
    4. <l-price
    5. wx:if="{{p.cutPrice(data.price,data.discount_price).display}}"
    6. deleted
    7. value="{{p.cutPrice(data.price,data.discount_price).price}}">
    8. l-price>

    直接在wxml下写:

    类似于html的