一. radio 与 radio-group
radio 为表单组件中的单选,适用于只能选择一个值的场景.
radio 的常用属性如下:
radio-group 为单项选择器,内部由多个 <radio> 组成。
其属性如下, 为bindchange, 当其内部的radio的值发生改变时, 触发该事件.
二 .代码示例
wxml的代码如下.
使用wx:for
来进行循环遍历出数组中的值 . 并对radio中的color等属性,进行动态的赋值.
并使用了bindchange属性,进行单选值绑定的监听.
<radio-group bindchange="changeme">
<block wx:for="{{array}}">
<radio color='{{item.color}}' disabled='{{item.disabled}}' checked='{{item.checked}}' value='{{item.name}}'> {{item.value}}</radio>
</block>
</radio-group>
<view>{{myvalue}}</view>
js中的代码如下
定义了一个array数组.
// pages/radio/radio.js
Page({
data: {
array: [
{
id: "1001", name: "中国", value: "中国", checked: true, color: "blue", disabled: false, sdf: "sdfsd"
},
{
id: "1002", name: "日本", value: "日本", checked: false, color: "red", disabled: true, sdfsdf: "sfsdfd"
},
{
id: "1003", name: "美国", value: "美国", checked: true, color: "red", disabled: false
}
],
myvalue: "请选择一个国家"
},
changeme: function(e){
var value = e.detail.value;
this.setData({
myvalue: value
});
}
})
编译完成后的效果如图, 最后一个选中的是美国, 但在js的数组中有设置中国和美国的checked属性都为true, 是因为radio只能选中一个值, 先遍历中国,最后遍历美国, 以最后遍历为true的值为选中的值.
当选择中国时,下面的值也变为了这个, 代表绑定的changeme 方法也生效了
官方文档
https://developers.weixin.qq.com/miniprogram/dev/component/radio.html