微信小程序wxs的使用(当页面数据渲染前添加js操作)

JavaScript08

微信小程序wxs的使用(当页面数据渲染前添加js操作),第1张

小程序的wxs功能可以让wsmxl可以调用和编写js,基本上wxs和JS无关系,只是语法形式很相似。 如下写了两个关于时间的函数,并将它们导出, <wxs module="m1"> var getMax = function(flightDate) {     var now = getDate().getDate()     var flDate = getDate(flightDate).getDate()     if( now <flDate ){       return '+1'     }else{       return ''     } } var formartTime = function(flightDate,format){   if(flightDate){     var realDate = getDate(flightDate)     function timeFormat(num) {       return num <10 ? '0' + num : num     }     var date = {       "Y": timeFormat(realDate.getFullYear()),       "M": timeFormat(realDate.getMonth() + 1),       "d": timeFormat(realDate.getDate()),       "h": timeFormat(realDate.getHours()),       "m": timeFormat(realDate.getMinutes()),       "s": timeFormat(realDate.getSeconds()),       "q": Math.floor((realDate.getMonth() + 3) / 3),       "S": realDate.getMilliseconds(),     }     if (!format) {       format = "yyyy-MM-dd hh:mm:ss"     }     if( format == 'hh:mm' ){         return date.h+':'+date.m     }else{         return date.h+':'+date.m     }   }else{     return false   } } module.exports.getMax = getMax module.exports.formartTime = formartTime </wxs> 可在页面添加如下使用: m1.formartTime()  m1.getMax()

wxs脚本存在的意义是因为小程序的渲染机制决定的。小程序的webview 与 js逻辑渲染的分离导致小程序在某些场景需要高频触发this.setData() 时会出现卡顿现象,为了解决卡顿场景wxs 脚本顺势而生。

官方介绍:

wxs脚本的解决方案:wxs脚本是运行在wxml视图层的,避开了跨线程通信的成本。wxs可以直接操作wxml的视图元素,也可以充当类似vue 中computed的角色来格式化数据,减少调用this.setData()的次数,减少性能损耗。

wxs 需要注意的是只能通过console.log()来调试脚本,无法通过debugger和断点进行。

使用实例详看官方文档( https://developers.weixin.qq.com/miniprogram/dev/framework/view/interactive-animation.html )

注意细节的理解以及官方在文档末尾提供的参考示例。

工具类函数

将wxs引入到wxml中,设置module名为tool,引入的时候,wxs标签src填写相对路径(绝对路径无效)

wxml中使用函数

无论是WXS函数和JS函数都是能操作data数据,很多时候通过JS函数得到data,然后用WXS函数处理。

验证邮箱