话题来源

  1. 临下班了还开会,有点生气唷=.=,去会议室一屁股刚坐下,我隔壁的小姐姐小声地问了我一个问题:你有用过wxs么?是怎么用的?<br /> 我:一般是拿来对数据进行处理,比如后端接口返回的时间戳格式的,我们要展示成yyyy-mm-dd格式.<br /> 小姐姐:那这个JS也可以做呀,直接放在数据请求回来以后,不是么?<br /> 我:嗯,确实是的。<br /> 额嗯,很尴尬,我也不知道为啥我好像只拿来处理过我刚描述的场景😳。<br />越学发现不会的东西越多,那就总结起来啊👌

什么是wxs?

wxs区别于js, wxs可直接作用到视图层,而不需要逻辑层跟视图层的setData数据交互。

适用场景: 适合优化小程序的频繁交互操作中。

wxs用法

1. 过滤器

可像函数一样调用wxs中的方法。

举个例子🌰:这里仅简单说明怎么用,实际业务肯定没这么简单=.=

  1. // wxml
  2. <wxs src='../../wxs/time.wxs' module="time"/>
  3. <view>{{ time.sayHello() }}</view>
  4. // wxs
  5. function sayHello () {
  6. return 'wxs进行处理后的东东'
  7. }
  8. module.exports = {
  9. sayHello: sayHello
  10. }

2. 复杂动画

若依赖js逻辑层,会需要大量、频繁的数据通信,卡顿是不可避免的。而采用wxs的话不需要频繁setData()从而导致的实时大量数据通信,节省性能的考虑。

实现需求:有个box盒子,用原生实现拖拽的效果。
实现思路:监听手势动作,记录每次移动的left/top,实时更新给到视图层。
实现code如下👇:

  1. // wxml
  2. <view>
  3. <view class="touch-cont">
  4. <view class="touch-box" style="left: {{left}}px; top: {{top}}px" bindtouchstart="bindtouchstart" bindtouchmove="bindtouchmove">我是可拖动的box</view>
  5. </view>
  6. </view>
  7. // js文件
  8. Page({
  9. data: {},
  10. bindtouchstart (event) {
  11. const touches = event.touches[0]
  12. this.startX = touches.pageX
  13. this.startY = touches.pageY
  14. },
  15. bindtouchmove (event) {
  16. const touches = event.touches[0]
  17. const resX = this.startX + touches.pageX
  18. const resY = this.startY + touches.pageY
  19. this.setData({
  20. left: resX,
  21. top: resY
  22. })
  23. },
  24. })
  25. // wxss文件
  26. .touch-cont {
  27. position: relative;
  28. width: 600rpx;
  29. height: 600rpx;
  30. overflow: hidden;
  31. background: #eeeeee;
  32. }
  33. .touch-box {
  34. position: absolute;
  35. top: 0;
  36. left: 0;
  37. width: 200rpx;
  38. height: 200rpx;
  39. background: #2c2c2c;
  40. color: #ffffff;
  41. }

该实现思路会导致频繁的setData,即存在频繁的数据通信,卡顿是有的,不信你cooy代码试试看。

那我们思考下,如果换成wxs来实现的话,效果怎么样呢?
实现思路:通过wxs可直接绑定在wxml标签上,通过selectComponent去选中操作的元素从而达到修改left/top的效果。

  1. // wxml
  2. <wxs src='./demo.wxs' module='demo'></wxs>
  3. <view>
  4. <view class="touch-cont">
  5. <view class="touch-box" bindtouchstart="{{demo.touchstart}}" bindtouchmove="{{demo.touchmove}}">我是可拖动的box</view>
  6. </view>
  7. </view>
  8. // wxs文件
  9. var startX = 0
  10. var startY = 0
  11. var touchstart = function (event) {
  12. var touch = event.touches[0]
  13. startX = touch.pageX
  14. startY = touch.pageY
  15. }
  16. var touchmove = function (event, ins) {
  17. var touch = event.touches[0]
  18. var resX = startX + touch.pageX
  19. var resY = startY + touch.pageY
  20. ins.selectComponent('.touch-box').setStyle({
  21. left: resX + 'px',
  22. top: resY + 'px'
  23. })
  24. }
  25. module.exports = {
  26. touchstart: touchstart,
  27. touchmove: touchmove
  28. }
  29. // js
  30. js不需要任何额外的东西

该方案下,js文件不需要写任何额外的东西,也没有频繁的逻辑层跟视图层通信,卡顿感少很多。

写在最后

  1. 一个东西的出现肯定是为了解决问题的,所以尝试多去思考该东西出现的背景,也许你会对技术有更大的cover力!