Vue3+Tailwind下实现单选按钮点击二次确认及选中状态控制
单选按钮二次确认选中逻辑问题
需求描述
实现交互规则:点击单选按钮时弹出确认提示,仅当用户确认选择后,才将对应选项设为选中状态。
初期完成弹窗开发后存在异常:用户点击取消时,被点击的单选按钮仍会被选中,无法通过绑定方法控制选中状态的切换。
初始实现代码
单选按钮模板部分
<div class="grid grid-cols-2 m-10 max-w-md mx-auto"> <div class="relative"> <input class="sr-only peer" type="radio" value="A" name="answer" id="answer_a" @click="methodA()" checked> <label class="flex justify-center text-white font-bold py-3 px-2 bg-lightGray rounded-l-lg cursor-pointer peer-checked:bg-darkgreen " for="answer_a">A</label> </div> <div class="relative"> <input class="sr-only peer" type="radio" value="B" name="answer" id="answer_SP" @click="methodB()"> <label class="flex justify-center text-white font-bold py-3 px-2 bg-lightGray rounded-r-lg cursor-pointer peer-checked:bg-darkgreen" for="answer_b">B</label> </div> </div>
弹窗逻辑初始代码
async methodA() { VueSimpleAlert.confirm("Are you sure you want to select A?", "Warning", "question", {}) .then(async confirmed => { if (confirmed) { this.bouleanA = true; this.$refs.answer_A.checked = false; this.$refs.answer_B.checked = true; } else { this.bouleanA = false; this.$refs.answer_A.checked = true; this.$refs.answer_B.checked = false; } }) }, async methodB(){ VueSimpleAlert.confirm("Are you sure you want to select A?", "Warning", "question", {}) .then(async confirmed => { if (confirmed) { this.bouleanA = false; this.$refs.answer_A.checked=true; this.$refs.answer_B.checked= false; }else { this.bouleanA = true; this.$refs.answer_A.checked= false; this.$refs.answer_B.checked= true; } }) },
问题排查与修复
问题根因:VueSimpleAlert组件中,用户点击取消的操作会返回rejected状态的Promise,原代码错误使用then方法的else分支处理取消场景,导致取消后的单选按钮状态回滚逻辑从未被触发。
修复方案:将取消场景的状态回滚逻辑迁移到catch分支中执行,即可正常控制单选按钮的选中状态切换。
修复后可正常运行的代码如下:
async methodA() { VueSimpleAlert.confirm("Are you sure you want to select A?", "Warning", "question", {}) .then(async confirmed => { if (confirmed) { this.bouleanA = true; this.$refs.answer_A.checked = false; this.$refs.answer_B.checked = true; } }).catch(async err => { this.bouleanA = false; this.$refs.answer_A.checked = true; this.$refs.answer_B.checked = false; } ) }, async methodB(){ VueSimpleAlert.confirm("Are you sure you want to select A?", "Warning", "question", {}) .then(async confirmed => { if (confirmed) { this.bouleanA = false; this.$refs.answer_A.checked=true; this.$refs.answer_B.checked= false; } }).catch(async err => { this.bouleanA = true; this.$refs.answer_A.checked= false; this.$refs.answer_B.checked= true; } ) },
内容的提问来源于stack exchange,提问作者Maximilian
相关产品推荐
相关产品推荐

