Vue3输入框没有输入内容时进行文字提示,输入文字自动消失

先看效果:当输入框为空或者不符合要求是在输入框下方进行文字提示,检测到有输入内容则提示消失

1.html

要用到:class动态绑定样式和@input检测输入框状态,看代码

<el-input
    v-model="diauser"
    style="margin-bottom: 20px; width: 70%"
    placeholder="请输入账户"
    :prefix-icon="Avatar"
    clearable
    :class="{ error: diauserError }"
    @input="checkInput"
    ></el-input>
<small v-if="diauserError" class="error-message">账户不能为空且由6-16位字母、数字、下划线组成</small>

因为我写了多个输入框,所以我没有用div进行包裹,选择直接在el-input标签下直接使用span,但我想要的小字体所有把span换成了small(但在css中也做了字体大小修改)

2.js

js部分要定义为false,默认提示语为关闭状态

methods中代码为,使用管道符|| 进行逻辑判断的连接   (||==or或者)

if (
   this.diauser.trim() === "" ||
   !/(?=.*[A-Za-z_])[A-Za-z0-9_]{6,16}$/.test(this.diauser)
   ) {
     this.diauserError = true;
   }

还有一个检测输入框状态的方法

当点击输入框时触发checkInput方法,this.diauser.trim()会检查this.diauser是否为空或者不符合设定预期,this.diauserError是上方设置的布尔值,不符合预期就是true,其余都默认为false

3.css

定义提示语字体颜色、大小(格式)等

.error-message {
  color: red;
  font-size: 12px;
  margin-top: -20px;
}

如有错误,欢迎指正~!

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用 Vue 的数据绑定和计算属性来实现这个功能。具体实现步骤如下: 1. 在 Vue 的 data 中定义一个变量,用于存储 input 输入框的值。 ``` data() { return { inputValue: '' } } ``` 2. 在 input 输入框中绑定这个变量,并添加一个 change 事件。 ``` <input type="text" v-model="inputValue" @change="checkInput"> ``` 3. 在 methods 中定义 checkInput 方法,用于检查输入框的值是否为空。如果为空,将提示文字变成红色,并在提示文字中显示错误信息。 ``` methods: { checkInput() { if (this.inputValue === '') { this.$refs.errorMsg.style.color = 'red'; this.$refs.errorMsg.innerHTML = '输入框不能为空'; } else { this.$refs.errorMsg.style.color = 'black'; this.$refs.errorMsg.innerHTML = ''; } } } ``` 4. 在模板中添加一个 span 元素,用于显示错误信息,并添加一个 ref 属性,用于在 checkInput 方法中引用这个元素。 ``` <span ref="errorMsg"></span> ``` 5. 在计算属性中定义一个变量,用于控制提示文字的显示和隐藏。 ``` computed: { showErrorMsg() { return this.inputValue === ''; } } ``` 6. 在模板中绑定这个变量,并根据其值显示或隐藏提示文字。 ``` <span v-show="showErrorMsg" style="color: red">输入框不能为空</span> ``` 完整的代码如下: ``` <template> <div> <input type="text" v-model="inputValue" @change="checkInput"> <span ref="errorMsg" v-show="showErrorMsg" style="color: red"></span> </div> </template> <script> export default { data() { return { inputValue: '' } }, methods: { checkInput() { if (this.inputValue === '') { this.$refs.errorMsg.style.color = 'red'; this.$refs.errorMsg.innerHTML = '输入框不能为空'; } else { this.$refs.errorMsg.style.color = 'black'; this.$refs.errorMsg.innerHTML = ''; } } }, computed: { showErrorMsg() { return this.inputValue === ''; } } } </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值