[英]In Vue3, how to check value of each radio button checked from a single group of radio buttons?
我刚刚开始使用 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-model 输出值,这很好......而且我还可以获得 CSS 样式的检查值......所以没关系..
但是,当检查一个输入字段(单选按钮)时,我会假设该按钮的ON
值定义了状态(也许我在这个假设中是错误的)......但是在我的代码中,如果我点击它转换为的任何按钮ON
但其他按钮也保持为ON
.. 我会假设如果按钮被选中,那么它将是ON
,如果不是,那么它将是......也许为null
? 还是false
? 我不知道...
我添加了一个名为@change
的showCheckedValue
函数,但不知道如何使其工作......
这是我要测试的脚本和样式设置...我什至尝试将v-model= "voted"
更改为每个按钮都有一个不同的按钮,例如v-model="voted1"
和v-model="voted2"
等等上..但这也没有用..
所以这里的问题是如何输出或复制一组单选按钮的检查值? 如果其中一个被选中,它应该是true
或on
而其他的应该是false
或null
?
这是我在 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
可以与之绑定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.