項目開發中有一需求,在ABCD四個選項中,選擇一正確選項,即選中一radio便獲取對應input的內容,存入數據庫
如圖:
當點擊radio A 時,自動獲取後面input框中的內容
前提:我選用的是組件庫中的單選框組
根據查閱element-ui的官方API得知,如果使用了單選按鈕組,在el-radio-group中綁定v-model,在el-radio中設置好label,當設置了change事件後,選擇不同的單選按鈕,即可獲取不同的radio的label值
<template>
<!-- 單選按鈕組 -->
<el-radio-group v-model="radio" @change="getright">
<!-- 單選按鈕A -->
<el-radio :label="1">A</el-radio>
<el-radio :label="3">B</el-radio>
<el-radio :label="5">C</el-radio>
<el-radio :label="7">D</el-radio>
</el-radio-group>
</template>
JavaScript部分
<script>
export default {
data() {
return {
radio:"",//單選按鈕默認不選中
}
}
}
// methods部分
methods:{
getright(){
console.log("當前選中" + val);
}
}
</script>
效果如圖:當選擇不同的radio時,會打印不同radio對應的label值
但還沒有達到了我們的需求,獲取對應的input框的內容
只需要在getright方法中使用switch語句,定義全局變量接收即可
下面附上完整代碼
<template>
<!-- 單選按鈕組 -->
<div class="m_top">
<el-radio-group v-model="radio" @change="getright">
<!-- 選項A -->
<el-radio :label="1">A</el-radio>
<span>
<el-input
v-model="IA_inputw"
style="width:600px;"
></el-input>
</span>
<!-- 選項B -->
<el-radio :label="3">B</el-radio>
<span>
<el-input
v-model="IB_inputw"
style="width:600px;"
></el-input>
</span>
<!-- 選項C -->
<el-radio :label="5">C</el-radio>
<span>
<el-input
v-model="IC_inputw"
style="width:600px;"
></el-input>
</span>
<!-- 選項D -->
<el-radio :label="7">D</el-radio>
<span>
<el-input
v-model="ID_inputw"
style="width:600px;"
></el-input>
</span>
</el-radio-group>
</div>
</template>
JavaScript部分
<script>
export default {
data() {
return {
radio:"",//單選按鈕默認不選中
IA_inputw,選項A
IB_inputw,選項B
IC_inputw,選項C
ID_inputw,選項D
}
}
}
// methods部分
methods:{
getright(){
getright(){
switch (this.radio) {
case 1:
this.currentValue = this.IA_inputw;
break;
case 3:
this.currentValue = this.IB_inputw;
break;
case 5:
this.currentValue = this.IC_inputw;
break;
case 7:
this.currentValue = this.ID_inputw;
break;
}
console.log("正確答案是:" + this.currentValue);
}
}
}
</script>