You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3中基于单选框值控制v-for生成选项的active状态

解决方案:根据Sides选择动态禁用Caps选项

1. 转为响应式选项数组

原代码中的capOptions和sideOptions是普通常量,修改其属性无法触发Vue响应式更新,需用ref包裹:

import { ref, watch } from 'vue'

const capOptions = ref([
  { name: 'No Cap', active: true },
  { name: '2-Sided', active: true },
  { name: '3-Sided', active: true },
  { name: '4-Sided', active: true },
])

const sideOptions = ref([
  { name: '2-Sided', active: true },
  { name: '3-Sided', active: true },
  { name: '4-Sided', active: true },
])

2. 监听选择变化并更新Caps状态

通过watch监听sides的选中值,动态修改Caps对应选项的active状态,同时处理选中项被禁用的边界情况:

const sides = ref(sideOptions.value[0])
const caps = ref(capOptions.value[0])

watch(sides, (newSelection) => {
  const targetCap = capOptions.value.find(opt => opt.name === '2-Sided')
  if (!targetCap) return

  if (newSelection.name === '2-Sided') {
    targetCap.active = false
    // 若当前选中的Caps是即将被禁用的选项,自动切换到第一个可用选项
    if (caps.value.name === '2-Sided') {
      caps.value = capOptions.value.find(opt => opt.active) || capOptions.value[0]
    }
  } else {
    targetCap.active = true
  }
})

3. 模板保持原有逻辑

原模板中已通过:disabled="!option.active"绑定禁用状态,响应式更新后视图会自动同步禁用效果,无需修改模板代码。

内容的提问来源于stack exchange,提问作者Charles Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 11:03:14