微信小程序wxs语法

wxs作用

wxml模板语法不支持函数调用。如果需要在wxml模板语法中直接进行函数调用 那么使用wxs语法实现

使用wxs注意事项

  • 不支持ES6语法
  • 无法调用微信小程序的api
  • 无法调用Page/App中使用JavaScript编写的脚本
  • 模块导出必须使用CJS规范

wxs使用方式

  • 方式一: 独立.wxs文件
  • 方式二: .wxml内部使用嵌入<wxs>标签

wxs使用方式一

编写wxs脚本

// /tools/formatTime.wxs

// 格式化时间
var padLeft =  function(time) {
    
    
  time = time + '' // 转换成字符串 可以调用字符串API
  return ('00'+time).slice(time.length)
}
// 时间转换
var calcTime = function(time) {
    
    
  var minutes = Math.floor(time / 60)
  var seconds = Math.floor(time) % 60
  return padLeft(minutes) + ':' + padLeft(seconds)
}
// wxs不支持ES6语法 必须完整
module.exports = {
    
    
  calcTime:calcTime
}

导入wxs脚本
指定module属性

<wxs src="/tools/formatTime.wxs" module="formatTime"></wxs>

数据

Page({
    
    
  data: {
    
    
    musicToalTime: 232,
})

使用模块提供的API

<view>{
   
   {formatTime.calcTime(musicToalTime)}}</view>

效果
在这里插入图片描述

wxs使用方式二

业务层数据

// pages/index/index.js

Page({
    
    
  data: {
    
    
    shoppingCar:[
      {
    
    id:'001',name:'舒肤佳净透啫喱沐浴露',count:2,price:44.90 },
      {
    
    id:'002',name:'iphone14pro',count:1,price:8899.00 },
    ]
  }
})

视图层

// pages/index/index.wxml

// wxs脚本
<wxs module="formatPrice">
  var addRmb = function(price) {
    
    
    return '¥' + price 
  }
  var totalPrice = function(shooping) {
    
    
    return addRmb(shooping.reduce(function (pre,item) {
    
    
      return pre + item.count * item.price 
    },0).toFixed(2))
   
  }
  module.exports = {
    
    
    totalPrice: totalPrice
  }
</wxs>

<view>{
    
    {
    
    formatPrice.totalPrice(shoppingCar)}}</view>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43364458/article/details/129341897