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

Vue 3 如何通过条件判断动态控制HTML属性是否渲染?

方案1:直接修改属性绑定表达式

直接把原来的三元表达式调整为无效值时返回undefined即可,Vue会自动移除值为undefined/null的属性:

<InputNumber v-model:value="example[index].number" 
     :min="collector.attr[0] != null ? collector.attr[0] : undefined" 
     :max="collector.attr[1] != null ? collector.attr[1] : undefined" 
     :step="0.01"
     style="min-width: 120px;"/>

如果你的项目支持ES2020+语法,也可以用更简洁的空值合并运算符写法:

:min="collector.attr[0] ?? undefined"

注意不要用||运算符,否则合法的有效值0也会被判定为无效值,导致min属性被意外移除

方案2:动态属性绑定(更适合多条件属性场景)

如果需要条件判断的属性比较多,可以把属性封装成对象通过v-bind批量绑定,代码可读性更高:

<template>
  <InputNumber 
    v-model:value="example[index].number" 
    v-bind="inputNumberProps"
    :step="0.01"
    style="min-width: 120px;"
  />
</template>

<script setup>
import { computed } from 'vue'

// 其他业务逻辑省略
const inputNumberProps = computed(() => {
  const props = {}
  // 仅当attr[0]不为null/undefined时添加min属性
  if (collector.attr[0] != null) {
    props.min = collector.attr[0]
  }
  // 仅当attr[1]不为null/undefined时添加max属性
  if (collector.attr[1] != null) {
    props.max = collector.attr[1]
  }
  return props
})
</script>

两种方案都可以实现需求:有效最小值存在时挂载min属性,不存在时完全移除该属性,不会限制用户输入负数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 21:15:06