小程序出现大于两个是单选,是一个就switch,全代码包括页面和样式
时间: 2024-02-28 16:55:17 浏览: 26
以下是实现小程序选项选择的完整代码,包括页面、样式和逻辑处理。
```
<!-- index.wxml -->
<view class="container">
<view wx:if="{{options.length <= 2}}">
<view>请选择</view>
<switch wx:for="{{options}}" wx:key="index" style="margin-left: 10px;" bindchange="onSwitchChange" checked="{{index == selectedIndex}}">{{item}}</switch>
</view>
<view wx:else>
<view>请选择</view>
<radio-group bindchange="onRadioChange" style="margin-left: 10px;">
<radio wx:for="{{options}}" wx:key="index" value="{{index}}" checked="{{index == selectedIndex}}">{{item}}</radio>
</radio-group>
</view>
</view>
```
```
// index.js
Page({
data: {
options: ['选项1', '选项2', '选项3', '选项4'], // 选项列表
selectedIndex: -1 // 当前选中的选项下标
},
// switch 选项变化事件处理函数
onSwitchChange: function(e) {
var index = e.currentTarget.dataset.index;
this.setData({
selectedIndex: index
});
},
// radio 选项变化事件处理函数
onRadioChange: function(e) {
var index = e.detail.value;
this.setData({
selectedIndex: index
});
}
})
```
```
/* index.wxss */
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
font-size: 16px;
}
.switch {
display: flex;
align-items: center;
margin-top: 10px;
}
.switch-text {
margin-left: 10px;
}
```
在这个示例中,我们首先在 data 中定义了选项列表 options 和当前选中的选项下标 selectedIndex。
在页面中,我们使用了 wx:if 和 wx:else 来判断选项数量是否小于等于 2,然后分别使用 switch 和 radio-group 渲染选项。在 switch 和 radio-group 中,我们使用 wx:for 循环渲染选项,并使用 checked 属性来表示当前选中的选项。
在事件处理函数中,我们使用 setData 函数来更新 selectedIndex 的值,这样,选项的选中状态就能够正确地显示了。
最后,我们还定义了一些样式,使页面显示更加美观。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)