小程序 : wxs语法基本使用 -- 类似于过滤器

第一步,创建wxs并导出

function formatPrice(price) {
  return "¥" + price
}

function calcPrice(books) {
  return "¥" + books.reduce(function(preValue, item) {
    return preValue + item.price
  }, 0)
}

// 对count进行格式化
function formatCount(count) {
  count = Number(count)
  if (count >= 100000000) {
    return (count / 100000000).toFixed(1) + "亿"
  } else if (count >= 10000) {
    return (count / 10000).toFixed(1) + "万"
  } else {
    return count
  }
}


// 必须导出后, 才能被其他地方调用: 必须使用CommonJS导出
module.exports = {
  formatPrice: formatPrice,
  calcPrice: calcPrice,
  formatCount: formatCount,
}

 

2.使用 

<!-- 独立的文件, 通过src引入 -->
<wxs module="format" src="/utils/format.wxs"></wxs>

<view class="books">
  <block wx:for="{{books}}" wx:key="id">
    <view>name:{{item.name}}-price:{{format.formatPrice(item.price)}}</view>
  </block>
</view>

<view class="total">总价格: {{format.calcPrice(books)}}</view>

<view>------------题目练习------------</view>
<view class="count">播放量: {{format.formatCount(playCount)}}</view>

 

3.数据 

// pages/05_learn_wxs/index.js
Page({
  data: {
    books: [
      { id: 111, name: "代码大全", price: 98, coverURL: "" },
      { id: 112, name: "你不知道JS", price: 87, coverURL: "" },
      { id: 113, name: "JS高级设计", price: 76, coverURL: "" },
    ],
    playCount: 2232,
    duration: 255,
    currentTime: 65
  },
})

 

posted @ 2022-09-07 13:40  杨建鑫  阅读(44)  评论(0编辑  收藏  举报