uni-app checkbox的使用实例
时间: 2025-08-15 07:11:46 浏览: 16
在 `uni-app` 中,`checkbox` 组件用于实现复选框功能,允许用户从多个选项中选择一个或多个。以下是 `checkbox` 组件的基本使用方法示例。
### 基本用法
```html
<template>
<view>
<checkbox-group @change="checkboxChange">
<label v-for="(item, index) in checkboxItems" :key="index">
<checkbox :value="item.value" :checked="item.checked" /> {{ item.name }}
</label>
</checkbox-group>
</view>
</template>
```
```javascript
<script>
export default {
data() {
return {
checkboxItems: [
{ name: '选项1', value: '1', checked: false },
{ name: '选项2', value: '2', checked: true },
{ name: '选项3', value: '3', checked: false }
]
};
},
methods: {
checkboxChange(e) {
const checkedValues = e.detail.value;
console.log('选中的值:', checkedValues);
}
}
};
</script>
```
### 说明
- `checkbox-group` 是一个包裹组件,用于包裹多个 `checkbox` 组件,并通过 `@change` 事件监听选中状态的变化。
- `checkbox` 组件的 `value` 属性用于标识该复选框的值,`checked` 属性控制该复选框是否默认选中。
- `checkboxChange` 方法用于处理复选框组的选中状态变化,`e.detail.value` 返回当前选中的值数组。
### 自定义样式
如果需要自定义复选框的样式,可以通过 `label` 和 `checkbox` 结合使用,并通过 `class` 或 `style` 属性进行样式控制。
```html
<template>
<view>
<checkbox-group @change="checkboxChange">
<label class="custom-checkbox" v-for="(item, index) in checkboxItems" :key="index">
<checkbox :value="item.value" :checked="item.checked" />
<text>{{ item.name }}</text>
</label>
</checkbox-group>
</view>
</template>
```
```css
<style>
.custom-checkbox {
display: flex;
align-items: center;
margin: 10px 0;
}
</style>
```
### 注意事项
- `checkbox-group` 的 `@change` 事件会在复选框的状态发生变化时触发,返回一个包含所有选中值的数组。
- `checkbox` 组件的 `value` 必须是字符串类型,否则可能无法正确识别选中状态。
通过上述示例,可以轻松实现 `uni-app` 中 `checkbox` 组件的基本功能,并根据需求进行扩展和样式调整。
阅读全文
相关推荐



















