記錄一下封裝vue 帶提示的 input 基礎組件


一、實現效果

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>

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM