在Vue3中,如何检查从单个单选按钮组中检查的每个单选按钮的值



我刚刚开始使用Vue3进行训练,非常喜欢它。但我遇到了一些问题,这些问题似乎用香草JS更容易(直观(。

我有这组单选按钮,它们具有相同的name

<template>
<div class="container">
<div class="inputs">
<div class="input">
<input
id="01-01"
v-model="voted"
type="radio"
name="VP-01"
@change="showCheckedValue"
/>
<label for="01-01">1</label>
</div>
<div class="input">
<input
id="01-02"
v-model="voted"
type="radio"
name="VP-01"
@change="showCheckedValue"
/>
<label for="01-02">2</label>
</div>
<div class="input">
<input
id="01-03"
v-model="voted"
type="radio"
name="VP-01"
@change="showCheckedValue"
/>
<label for="01-03">3</label>
</div>
<div class="input">
<input
id="01-04"
v-model="voted"
type="radio"
name="VP-01"
@change="showCheckedValue"
/>
<label for="01-04">4</label>
</div>
<div class="input">
<input
id="01-05"
v-model="voted"
type="radio"
name="VP-01"
@change="showCheckedValue"
/>
<label for="01-05">5</label>
</div>
</div>
<div class="checked">
<div class="one">Checked value of 1 : {{ voted }}</div>
<div class="one">Checked value of 2 : {{ voted }}</div>
<div class="one">Checked value of 3 : {{ voted }}</div>
<div class="one">Checked value of 4 : {{ voted }}</div>
<div class="one">Checked value of 5 : {{ voted }}</div>
</div>
<div class="voted">
{{ voted }}
</div>
</div>
</template>

我可以用v模型输出值,这很好。。。我还可以得到CSS样式的检查值。。。所以没关系。。

但是,当选中一个输入字段(单选按钮(时,我会假设该按钮的ON值定义了状态(也许我的假设是错误的(。。。但在我的代码中,如果我点击任何按钮,它都会转换为ON,但其他按钮也会保留为ON。。我假设如果按钮被选中,那么它将是ON,如果没有,那么它会是。。。可能是null?还是false?我不确定。。。

我添加了一个名为@change的showshowCheckedValue函数,但不知道如何使其工作。。。

这是我要测试的脚本和样式设置。。。我甚至试图将v-model= "voted"更改为每个按钮都有一个不同的v-model="voted1"v-model="voted2"等等,但这也不起作用。。

所以问题来了如何输出或复制一组单选按钮的检查值?如果其中一个被选中,它应该是trueon,其他应该是falsenull

这是我在codepen上测试的链接。。https://codepen.io/alimbolar/pen/OJvmNQB


<script setup>
import { ref } from "vue";
const voted = ref(null);
// const voted2 = ref(null);
// const voted3 = ref(null);
// const voted4 = ref(null);
// const voted5 = ref(null);
</script>
<!-- Use preprocessors via the lang attribute! e.g. <style lang="scss"> -->
<style>
html {
box-sizing: border-box;
}
#app {
border: 1px solid red;
margin: 50px;
display: grid;
place-items: center;
height: 100vh;
}
.container {
display: flex;
flex-direction: column;
justify-content: space-evenly;
width: 100%;
height: 100%;
}
.inputs {
border: 1px solid green;
padding: 20px;
width: 100%;
display: flex;
justify-content: space-evenly;
}
.checked {
border: 1px solid red;
width: 100%;
display: flex;
}
.checked > * {
text-align: center;
font-size: 0.8rem;
padding: 1rem;
}
.voted {
text-align: center;
text-transform: uppercase;
border: 1px solid orange;
padding: 10px;
}
input:checked + label {
color: red;
}
</style>

您需要为每个radio button提供一个value,以便voted ref可以与其绑定。

请检查代码笔

最新更新