一、实现效果
1、当 input 输入框不符合要求且在 input 失焦时显示提示词,符合要求隐藏提示词



2、实现 input 组件基本功能
二、组件实现代码
1、HTML
<template> <div class="labelInput"> <span class="title">{{title}}</span> <input type="text" :value="currentValue" @input="inputload" :minlength="minLength" :maxlength="maxLength" :placeholder="placeHolder" @blur="blur" class="input"> <span v-show="showHint" class="hint">{{hint}}</span> </div> </template>
2、js
<script>
export default {
props: {
title: {
type: String,
default: '标题'
},
maxLength: {
type: Number,
default: 30
},
minLength: {
type: Number,
default: 1
},
hint: {
type: String,
default: `提示内容`
},
placeHolder: {
type: String,
default: `标题`
},
value: { // 父组件传来的 input 值
type: [String, Number],
default: ''
}
},
data () {
return {
currentValue: this.value, // 将父组件传的 input 值与子组件 input 的值绑定
showHint: true // 是否显示 提示文字
}
},
watch: {
value (newVal) { // value 改变设置 currentValue 的值 (双向绑定 父 => 子)
this.setCurrentValue(newVal)
}
},
methods: {
setCurrentValue (newVal) { // 设置当前值
if (newVal === this.currentValue) {
return
}
this.currentValue = newVal
},
inputload (e) { // input 值改变触发
let value = e.target.value
this.$emit('input', value) // 派发事件,最新的值作为参数 这里的事件名 input 可以随便命名,v-model 最后还是会默认取 input 事件 (双向绑定 子 => 父)
},
blur () { // input 失焦校验 currentValue
if (this.currentValue.length > this.maxLength || this.currentValue.length < this.minLength) {
this.showHint = true
} else {
this.showHint = false
}
}
}
}
</script>
3、css
<style lang="stylus" scoped> .labelInput width 100% height 60px box-sizing border-box padding 5px 0 position relative .title color #BFBFBF font-size 13px .input width 100% height 34px border none border-bottom 1px solid #c3cad7 box-sizing border-box color #4d6b8a font-size 14px &:focus outline none border-bottom 2px solid #439ad9 .hint font-size 13px color #3598dc position absolute display block </style>
三、使用
<hint-input v-model="weiboTitle"
hint="文章标题,11到30个字内"
:minLength="11"
class="weibo-title"></hint-input>
