y:[1,2,3,4]
},
switch: function(e){
const length = this.data.objectArray.length
for(let i=0; i < length; i++){
const x = Math.floor(Math.random() * length)
const y = Math.floor(Math.random() * length)
const temp = this.data.objectArray[x]
this.data.objectArray[x] = this.data.objectArray[y]
this.data.objectArray[y] = temp
}
this.setData({
objectArray:this.data.objectArray
})
},
addToFront:function(e){
const length = this.data.objectArray.length
this.data.objectArray = [{id:length, unique: 'unique_'+length}].concat(this.data.objectArray)
this.setData({objectArray:this.data.objectArray})
},
addNumberToFront:function(e){
this.data.numberArray = [this.data.numberArray.length + 1].concat(this.data.numberArray)
this.setData({
numberArray:this.data.numberArray
})
}
})
(可以小程序开发工具中预览效果,注意将wxml片段和j片段分别保存在.wxml文件和.js文件中)
页面布局模板
WXML支持使用模版(template)。可以在模版中定义代码片段,然后在别的地方引用。
定义模版时,使用name属性为模版命名。 在<template />标签内定义模版代码片段,下面是一段电影列表页面显示电影评级星数的模版:
<template name="starsTemplate">
<view class="stars-container">
<view class="stars">
<block wx:for = "{{stars}}" wx:for-item="i">
<image wx:if="{{i}}" src="/images/icon/star.png"></image>
<image wx:else src="/images/icon/none-star.png"></image>
</block>
</view>
<text class="star-score">{{score}}</text>
</view>
</template>
使用is属性,声明需要使用的模版,还需要将模版所需要的data传入,例如:
<!--wxml-->
<template is="starsTemplate" data="{{stars:stars,score:average}}"/>
is 属性还可以借助 Mustache 语法,来动态决定具体需要渲染哪个模版:
<template name="fir">
<view> first </view>
</template>
<template name="sec">
<view> second </view>
</template>
<block wx:for="{{[1,2,3,4,5]}}">
<template is="{{item % 2 == 0 ? 'fir' : 'sec'}}" />
</block>
模版拥有自己的作用域,它只能使用data传入的数据。
文件引用
WXML提供两种文件引用的方式:import 和 include。
import 可以在当前文件中使用目标文件定义的template,例如,在 item.wxml 中定义了一个叫 item 的 template:
<!-- item.wxml-- >
<template name = "item">
<view>{{text}}</view>
</template>
在index.wxml中引用item.wxml,就可以使用item模版:
<import src = "item.wxml" />
<template is = "item" data = "{{text: 'forbar'}}" />
import是有作用域概念的,只会引用目标文件中定义的template,而不能引用目标文件嵌套import的template。比如,C import B , B import A,在C中可以使用B定义的template,在B中可以使用A定义的template,但是C不能使用A中定义的template。
include可将目标文件除模版代码(<template />)块的所有代码引入,相当于拷贝到include位置。
<!-- index.wxml -->
<include src = "header.wxml" />
<view> body </view>
<include src = "footer.wxml" />
<!-- header.wxml -->
<view> header </view>
<!-- footer.wxml -->
<view> footer </view>
事件绑定
事件的定义
事件是视图层到逻辑层的通信方式,可以将用户的行为反馈到逻辑层进行处理。事件绑定到组件上,当触发事件时,就会执行逻辑层中对应的事件处理函数。事件对象可以携带额外的信息,如id、dataset、touches。
事件的使用
小程序与用户的交互