Vue2单选框点击后可取消勾选的一种解决办法
因为原生html5的单选框一旦选中后无法指定取消勾选,于是在实践中尝试出了以下方法
通过鼠标事件来取消勾选
待修改的原生html代码
<template>
<input type="radio" name="gender">男
<input type="radio" name="gender">女
<template/>
思路是,在点击事件发生前判断radio的 checked
的值,如果为 false
,将被点击的标签的 checked
改为 false
但是如果将方法绑定在 click
事件上,实际不会获得点击前的 checked
值,只会获得点击事件完成后的值
<template>
<input type="radio" name="gender" @click="radioClick">男
<input type="radio" name="gender">女
<template/>
methods:{
redioClick(e){
console.log('checked-0', e.target.checked)
// 控制台输出:checked-0 true
}
}
于是改用 mousedown
事件,但是radio标签本身具有click事件,因此无论在何种状态下点击单选框,radio都会自动勾选上,所以为了阻碍click,用vue的事件修饰符 prevent
来阻止click发生
<template>
<input type="radio" name="gender" @mousedown="radioClick" @click.prevent>男
<input type="radio" name="gender">女
<template/>
methods:{
redioClick(e){