Nuxt.js中Vuetify表格v-radio无法单选问题求助
问题修复方案
核心问题分析
- 每个表格单元格都嵌套了独立的
v-radio-group,且所有组绑定同一个变量,导致选中任意单选框时,所有组的绑定值同步变化,出现全选现象。 - 初始将
answer定义为数组,但单选场景仅需存储单个选中值,数组类型会导致校验和选中逻辑混乱。 - 表格结构不符合语义,数据行错误放在
<thead>中。
修复后的完整代码
<template> <v-radio-group class="mt-0" v-model="selectedColumn" :rules="answerRule"> <table> <thead> <tr> <th>Pilihan</th> <th v-for="(option, key) in columns" :key="`col-${key}`"> {{ option.value }} </th> </tr> </thead> <tbody> <tr v-for="(row, rowKey) in rowsCols" :key="`row-${rowKey}`"> <th>{{ row.value }}</th> <td v-for="(col, colKey) in row.columns" :key="`cell-${rowKey}-${colKey}`"> <v-radio class="radioA" solo :value="col.value" /> </td> </tr> </tbody> </table> </v-radio-group> </template> <script> export default { props: ['question'], data() { return { rowsCols: this.question.options, selectedColumn: null, columns: this.question.optionsColumns, answerRule: [] } }, methods: { async update() { try { const payload = { questionId: this.question.id, value: { [this.question.question]: this.selectedColumn }, questionName: this.question.question } await this.$store.commit('answers/update', payload) } catch (err) { this.$store.commit('alerts/show', { type: 'error', message: err.response ? this.$t(err.response.data.message) : this.$t('SERVER_ERROR') }) } } }, beforeMount() { if (this.question.required) { this.answerRule.push(v => v !== null || this.$t('QUESTION_REQUIRED')) } }, watch: { selectedColumn: { handler() { this.update() } } } } </script>
关键修改说明
- 移除嵌套单选组:仅保留最外层
v-radio-group,让所有单选按钮同属一个组,实现全局单选效果。 - 调整绑定变量类型:将数组
answer改为单个变量selectedColumn,匹配单选场景的存储需求。 - 修正表格结构:把数据行移到
<tbody>中,符合HTML语义规范。 - 生成指定JSON格式:在
update方法中,按{ question: 选中列 }的要求组装提交数据。 - 改用监听触发更新:通过
watch监听选中值变化,替代原单元格内的@change事件,逻辑更简洁。
内容的提问来源于stack exchange,提问作者JS24
相关产品推荐
相关产品推荐

