开始
微信小程序数据绑定
data(数据)
在js文件中,Page({})实例中
data: {
//字符串
message:'数据',
//数组
items: [
{ name: 'USA', value: '美国' },
{ name: 'CHN', value: '中国', checked: 'true' },
{ name: 'BRA', value: '巴西' },
{ name: 'JPN', value: '日本' },
{ name: 'ENG', value: '英国' },
{ name: 'TUR', value: '法国' },
]
},
function() 方法
//方法名
checkboxChange: function (e) {
console.log('checkbox发生change事件,携带value值为:', e.detail.value)
},
与wxml页面绑定
使用大胡子语句{{}} 绑定字符串 当{{1+1}} 可以表示字面量和逻辑运算
<view>{{message}}</view>
在CheckBox里面只要是字符串就为true
<!-- 在CheckBox里面checked="" 只要里面是字符串就为true -->
<checkbox checked="true"></checkbox> true
<checkbox checked="false"></checkbox> true
<checkbox checked="{{false}}"></checkbox> false
使用for循环 绑定数组
wx:for-item=“aaa” 是添加别名
<!-- wx:for遍历checkbox -->
<!-- wx:for-item起别名也可以直接item.name -->
<view wx:for="{{todos}}" wx:for-item="aaa">
<view>
<!-- 下标 -->
<text>{{index}}</text>
<checkbox checked="{{aaa.complated}}"></checkbox>
<text>{{aaa.name}}</text>
</view>
</view>
用wx:for 和wx:if 来写九九乘法表
<view wx:for="{{[1,2,3,4,5,6,7,8,9]}}" wx:for-item="i">
<view wx:for="{{[ 1,2,3,4,5,6,7,8,9]}}" wx:for-item="j">
<!-- wx:if 是用来根据Boolean值来决定隐藏或者显示 -->
<view wx:if="{{i <= j}}">
{{i}}*{{j}}={{i*j}}
</view>
</view>
</view>
界面层处理事件函数
点击事件 bind+事件名
<view bindtap="btn">点我</view>
阻止冒泡 catch+事件名
<!-- 阻止冒泡 -->
<view style="width: 250px;height: 250px;background-color: red;position: relative;" bindtap="outter">
<!-- catchtap是阻止冒泡 -->
<view catchtap="inner"
style="width: 100px;height: 100px;background-color: blue;position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);">
</view>
</view>
事件传参
用data-xxx="" 来传参
<!-- 传参用data-xxx=""来传 js用e.target.dataset -->
<view bindtap="taphandel" data-name="zs">点击一</view>
<view bindtap="taphandel2" data-hello-world="ls">点击二</view>
用e.target.dataset来接收
taphandel:function (e){
console.log(e.target.dataset);
},
数据单向绑定
input 框数据与text的value值显示应该一样 用bindinput
<!-- 数据单向绑定 bindinput e.datail.value-->
<view>
<input value="{{message}}" bindinput="inputhandel" ></input>
<text>{{message}}</text>
</view>
this.setData({}) 方法是用来改变data中的数据 e.detail.value 是表示input 的value值
inputhandel:function(e){
// this.setData是用来改变data中的数据
this.setData({
message:e.detail.value
})
console.log(this.data)
}
数据绑定的关系图
wx:if 和hideen 之间的区别
wx:if 是当条件成立时才运行 而hidden是一直都会运行
如果一个元素在一个页面只出现一次那么使用wx:if比较好,如果一个元素在页面出现多次则使用hidden
<view class="container">
<view class="item">
<view class="title" bindtap="toggle">
<text>切换面板展示</text>
</view>
<!-- block 只是控制属性(wx:)的载体,页面渲染过程中没有实际意义 -->
<!-- <block wx:if="{{show}}">
<view class="content">
<text>
这里是内容。。。
这里是内容。。。
这里是内容。。。
</text>
</view>
<view class="content">
<text>
这里是内容。。。
这里是内容。。。
这里是内容。。。
</text>
</view>
</block> -->
<view class="content" hidden="{{!show}}">
<text>
这里是内容。。。
这里是内容。。。
这里是内容。。。
</text>
</view>
</view>
</view>
js
Page({
data: {
logs: [],
show:false
},
// 事件处理函数
toggle:function (){
this.setData({show:!this.data.show})
}
})