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

如何在Vue组件中正确编写链式V-If条件判断语句

问题根因

你的v-if指令存在两处语法错误:

  • 所有判断逻辑必须写在v-if绑定的同一对引号内部,你把&& "selectable"放在了引号外,Vue根本不会识别这部分为判断条件
  • selectable加了双引号会被识别为字符串字面量而非响应式变量,非空字符串的布尔值永远为true,完全达不到你判断变量状态的效果

修正后代码

<!-- 确认selectable是你当前组件内可访问的响应式变量/prop -->
<template v-if="props.row.primaryAlias && selectable">
  <SelectableAttribute attr-name="Alias" :attr-id="props.row.primaryAlias.id" :model-id="props.row.id" model-name="NewParticipant">
    {{ props.row.primaryAlias.value }}
  </SelectableAttribute>
</template>
<!-- 这里改用v-else-if避免props.row.primaryAlias为空时,直接取value抛出异常 -->
<template v-else-if="props.row.primaryAlias">
  {{ props.row.primaryAlias.value }}
</template>

可选简化写法

如果你想进一步减少重复代码,可以用动态组件实现:

<template v-if="props.row.primaryAlias">
  <component 
    :is="selectable ? 'SelectableAttribute' : 'span'"
    v-bind="selectable ? {
      attrName: 'Alias',
      attrId: props.row.primaryAlias.id,
      modelId: props.row.id,
      modelName: 'NewParticipant'
    } : {}"
  >
    {{ props.row.primaryAlias.value }}
  </component>
</template>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 14:54:01