1. 程式人生 > 其它 >input根據字元大小顯示元件(只適用於type=text)

input根據字元大小顯示元件(只適用於type=text)

HTML片段

<template>
    <el-input :value="actualValue" :disabled="disabled" :placeholder="placeholder" @input="change($event,maxLength)">
        <span class="el-input__count" v-if="showLength" slot="suffix"><span class="el-input__count-inner">{{this.fontLength}}/{{maxLength}}</span></span>
    </el-input>
</template>

JS片段

<script>
export default {
    name: 'InputLength',
    model: {
        prop: 'inputValue',
        event: 'change'
    },
    props: {
        //輸入的繫結值
        inputValue: {
            type: String,
            default: '',
        },
        disabled: {
            type: Boolean,
            
default: false }, placeholder: { type: String, default: '' }, //限定字元數 maxLength: { type: [String,Number], default: 99, }, showLength: { type: Boolean, default: true, }, }, data() {
return { fontLength: 0,//輸入的字元數 }; }, computed: { actualValue() { this.change(this.inputValue,this.maxLength) return this.inputValue; } }, methods: { //輸入字元判斷 change(v,n){ let temp = 0 let value = null; try { v.split('').forEach((val,i)=>{ if(/[\u4e00-\u9fa5]/.test(v[i])) temp +=2 else temp += 1 if(temp >= n+1) { value = v.substr(0,i); this.$emit('change', value); this.$message.warning("字元已經已達到最大限制!"); throw new Error(i) } }) } catch(i){ console.log('獲取錯誤+'+i,v); } // 實時監聽字元大小 this.fontLength = 0; // 直接點選檢視時顯示的文字 const fontSize = value?value:v; this.$emit('change', fontSize); if(fontSize){ for (var i = 0; i < fontSize.length; i++) { if (v[i].match(/[^\x00-\xff]/ig) != null){ //全形 this.fontLength += 2; //如果是全形,佔用兩個位元組 } else{ this.fontLength += 1; //半形佔用一個位元組 } } } } } } </script>

頁面呼叫

<InputLength v-model="activityForm.activityName" :maxLength="40" />

效果展示