比如,我们请求到的后端返回的图片格式是这样的:
"images": [
"http://p0.meituan.net/w.h/shaitu/d4c3f2dd57837a775864f89606663bf9140591.jpg",
"http://p0.meituan.net/w.h/shaitu/bc9f71b948489e5dc0458a77343a14b6191056.jpg",
"http://p0.meituan.net/w.h/shaitu/bd8371679c5d265bddae8624574ce1d0179483.jpg"
]
渲染在detail.wxml页面上
<view class="images">
<image wx:for="{{item.images}}" wx:key="*this" src="{{item}}"/>
</view>
图片不能正确显示,这是因为图片格式中的w.h需要替换成100.100才可以,怎么在当前页面对这个数据做一下处理呢?
我们可以借助wxs块来实现数据的优化。
- 每一个
.wxs
文件和<wxs>
标签都是一个单独的模块。 - 每个模块都有自己独立的作用域。即在一个模块里面定义的变量与函数,默认为私有的,对其他模块不可见。
- 一个模块要想对外暴露其内部的私有变量与函数,只能通过
module.exports
实现。
<!-- 4评论 -->
<view class="comments" wx:if="{{shop.comments.length}}">
<view class="item" wx:for="{{shop.comments}}" wx:key="*this">
...
<view class="images">
<image wx:for="{{item.images}}" wx:key="*this" src="{{utils.size(item)}}"/>
</view>
</view>
</view>
<wxs module="utils">
module.exports = {
size: function(input) {
return input.replace('w.h', '100.100')
}
}
</wxs>
如果想把这个wxs块单独抽出来,在其他地方使用,可以在includes文件下新建一个replace.wxs文件,内容如下:
var size=function(input) {
return input.replace('w.h', '100.100')
}
module.exports = {
size:size
}
在detail.wxml页面中引用,引用时src要使用相对路径,module指定名称:
<wxs src="../../includes/replace.wxs" module="utils" />
<!-- 4评论 -->
<view class="comments" wx:if="{{shop.comments.length}}">
<view class="item" wx:for="{{shop.comments}}" wx:key="*this">
...
<view class="images">
<image wx:for="{{item.images}}" wx:key="*this" src="{{utils.size(item)}}"/>
</view>
</view>
</view>