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" />

 

效果展示

input根据字符大小显示组件(只适用于type=text)

 

上一篇:Permissive Change for FCC Certification Application


下一篇:mysql普通索引与唯一索引区别