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

Vue3+TailwindCSS:登录错误时输入框边框未变红问题求助

解决Vue3+TailwindCSS登录错误时输入框边框不红的问题

问题根源

  1. 样式绑定逻辑错误:原代码中错误状态下仅设置了border-red-500(边框颜色),但移除了border-2(边框宽度),导致边框因无宽度而看不到红色。
  2. 冗余响应式变量:子组件中额外声明hasError并通过watch同步props.error完全没必要——Vue3的props在<script setup>中本身就是响应式的,可直接在模板中使用。

修复方案

修改Input.vue组件,去掉冗余代码并修正样式绑定:

<script setup>
import { ref, defineProps, defineEmits } from "vue";

const props = defineProps(["label", "type", "error"]);
const emit = defineEmits(["input-change"]);

let inputValue = ref("");

const updateInput = () => {
  emit("input-change", inputValue.value);
};
</script>

<template>
  <div class="input-container mt-8">
    <div class="flex w-[100%] justify-between">
      <label class="text-body font-bold pb-2">{{ label }}</label>
      <a
        href="#"
        class="text-xs underline"
        :class="{ block: type === 'password', hidden: type !== 'password' }"
        >Wachtwoord vergeten?</a
      >
    </div>
    <input
      :type="type"
      <!-- 修正class绑定:始终保留border-2,错误时替换边框颜色为红色 -->
      :class="{ 'border-red-500': props.error, 'border-primary-dark': !props.error }"
      class="w-[100%] p-2 rounded-md border-2 focus:outline-none"
      v-model="inputValue"
      @input="updateInput"
    />
  </div>
</template>

<style scoped></style>

可选优化

如果希望聚焦时错误状态的边框颜色保持红色,可调整focus样式:

<input
  :type="type"
  :class="{ 
    'border-red-500 focus:border-red-500': props.error, 
    'border-primary-dark focus:border-primary-dark': !props.error 
  }"
  class="w-[100%] p-2 rounded-md border-2 focus:outline-none"
  v-model="inputValue"
  @input="updateInput"
/>

验证

登录失败时,hasError.value = true会传递给Input组件的error props,模板直接通过props.error控制样式,输入框会显示2px宽的红色边框,问题解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 13:30:01