个人感觉用的时候注意以下几点:
1. 不要让WXS过多参与业务,发挥它的优势,只要它解决渲染性能问题
2. 如何向WMS传送参数
3. 如何让WMS和JS 进行交互
下面是解决拖动效果的WMS代码,文件名为move.wxs
var startX = 0 var startY = 0 var lastLeft = lastTop = 0 var flag var target_id ,target_top,target_left,target_width,target_height; var canvas_width = 200, canvas_height = 350 ; var hRatioH ; var stop = false function touchstart(event, ins) { // stop = false; var touch = event.touches[0] || event.changedTouches[0] startX = touch.pageX startY = touch.pageY var flag = false ; if( event.target.dataset.targetid != target_id){ flag = true; } target_id = event.target.dataset.targetid; target_top = event.target.dataset.targettop; target_left = event.target.dataset.targetleft; target_width = event.target.dataset.targetwidth ; target_height = event.target.dataset.targetheight; hRatioH = event.target.dataset.hratioh ; canvas_width = event.target.dataset.canvasw; canvas_height = event.target.dataset.canvash; if(flag){ lastLeft = target_left lastTop = target_top } } function touchmove(event, ins) { var touch = event.touches[0] || event.changedTouches[0] var pageX = touch.pageX var pageY = touch.pageY var left = pageX - startX + lastLeft var top = pageY - startY + lastTop startX = pageX startY = pageY lastLeft = left lastTop = top if(target_id ){ ins.selectComponent('.selectBox').setStyle({ left: left + 'px', top: top + 'px' }) ins.selectComponent('#'+ target_id).setStyle({ //使用选择器获取组件的引用 left: left + 'px', top: top + 'px' }) } } module.exports = { touchstart: touchstart, touchmove: touchmove }
使用时,在WXML文件中进行声明和引用,如:<wxs module="move" src="./move.wxs"></wxs>
然后在需要进行拖动控制的组件上绑定WXS事件,并可以通过 data-xxx 机制向wxs 脚本传入page中的data中的数据,如 data-targetid="{{selectbox.targetid}}" ,这样脚本内部可以通过
event.target.dataset.xxx 这样的方式获取到传入的值<view class="selectBox" catchtouchstart="{{move.touchstart}}" catchtouchmove="{{move.touchmove}}" catch:touchend="{{move.touchend}}" data-targetid="{{selectbox.targetid}}" data-targettop="{{selectbox.top}}" data-targetleft="{{selectbox.left}}" data-targetwidth="{{selectbox.width}}" data-targetheight="{{selectbox.height}}" data-hRatioH="{{hRatioH}}" data-canvasW="{{windowWidth}}" data-canvasH="{{windowHeight}}">
另外wxs脚本可通过callMethod方式调js脚本可以向JS传递数据,但是callMethod机制无法获取JS的返回值