UniApp 多个异步开关控制教程
UniApp 多个异步开关控制教程(uView 1.0 / Vue2 版本)
📘 教程简介
本文介绍如何在 UniApp + uView1.0 + Vue2 中实现 多个异步控制的开关组件,
每个开关可独立进行异步状态切换(例如调用后端接口),并在切换时显示加载状态。
🚀 效果演示
页面包含多个开关(如“设备1”、“设备2”…),用户点击切换时:
- 显示加载动画;
- 异步等待接口响应;
- 后端返回成功后更新状态。
🧩 完整示例代码
<template><view class="switch-list"><view class="switch-item" v-for="(item, index) in switchList" :key="item.id"><text>{{ item.name }}</text><u-switch:value="item.checked":loading="item.loading"@change="onSwitchChange(index, $event)"></u-switch></view></view>
</template><script>
export default {data() {return {switchList: [{ id: 1, name: '设备1', checked: true, loading: false, controlStatus: false },{ id: 2, name: '设备2', checked: false, loading: false, controlStatus: false },{ id: 3, name: '设备3', checked: true, loading: false, controlStatus: false }]};},methods: {onSwitchChange(index, val) {const item = this.switchList[index];if (item.controlStatus) {item.controlStatus = false;return;}item.loading = true;item.controlStatus = true;item.checked = !val;this.getResultFromServer(index, val);},getResultFromServer(index, targetStatus) {const item = this.switchList[index];setTimeout(() => {item.loading = false;item.controlStatus = true;item.checked = targetStatus;uni.showToast({title: `开关【${item.name}】已${targetStatus ? '开启' : '关闭'}`,icon: 'none'});}, 1500);}}
};
</script><style scoped>
.switch-list {padding: 20rpx;
}
.switch-item {display: flex;justify-content: space-between;align-items: center;padding: 20rpx 0;border-bottom: 1px solid #eee;
}
</style>
🔧 接口调用替换
如需调用真实后端接口,将 setTimeout 替换为:
uni.request({url: 'https://your.api/xxx',method: 'POST',data: { id: item.id, status: targetStatus },success: (res) => {item.loading = false;item.controlStatus = true;item.checked = targetStatus;},fail: () => {item.loading = false;item.controlStatus = false;uni.showToast({ title: '操作失败', icon: 'none' });}
});
✅ 教程总结
通过本示例,你可以:
- 支持多个
u-switch组件独立异步控制; - 使用
loading状态防止重复点击; - 结合
controlStatus避免循环触发; - 简单拓展为真实后端接口交互。
作者:ChatGPT(GPT-5)
更新时间:2025-11-08
