基于el-input改写的具有show-word-limit显示限制输入长度功能的输入框

芮明知
2023-12-01

背景

接手公司以前做的vue项目,是基于element2.3.9搭建的,现在要追加的功能需要在输入框显示限制输入长度,而2.3.9的element是没有show-word-limit功能的,如果升级element版本会导致项目中其他样式存在问题,所以只能自己添加功能代码了,磕磕绊绊终于写出来了~

代码片断

// 组件代码
<template>
    <div class="inputWord">
        <el-input id="inputWord" v-bind="$attrs" v-on="$listeners" :maxlength="maxlength" :value="value" auto-complete="off" @input="changeWord"></el-input>
        <span class="el-input__suffix">
            <span class="el-input__suffix-inner">
                <span class="el-input__count">
                    <span class="el-input__count-inner">
                        {{ wordLength }}/{{ maxlength }}
                    </span>
                </span>
            </span>
        </span>
    </div>
</template>

<script>
    export default {
        props: {
            value: {
                type: String,
                default: ''
            },
            maxlength: {
                type: Number,
                default: 0
            }
        },
        data() {
            return {
                wordLength: 0,
                flag: true
            };
        },
        created() {
            this.wordLength = this.value.length;
        },
        methods: {
            changeWord(val) {
                this.$nextTick(() => {
                    if (this.flag) {
                        this.wordLength = val.length;
                    }
                });
            }
        },
        mounted() {
        // 加这两个函数是为了避免输入中文过程中触发input事件
            let input = document.getElementById('inputWord');
            input.addEventListener('compositionstart', () => {
                this.flag = false;
            });
            input.addEventListener('compositionend', () => {
                this.flag = true;
            });
        }
    };
</script>
<style lang='scss' scoped>
.inputWord /deep/{
    position: relative;
    .el-input__inner{
        padding-right: 80px;
    }
}
.el-input__suffix{
    position: absolute;
    height: 100%;
    right: 5px;
    top: 0;
    text-align: center;
    color: #c0c4cc;
    transition: all .3s;
    pointer-events: none;
}
.el-input__count {
    height: 100%;
    display: inline-flex;
    align-items: center;
    color: #909399;
    font-size: 12px;
}
.el-input__count-inner {
    background: #fff;
    line-height: normal;
    display: inline-block;
    padding: 0 5px;
}
</style>

// 组件的引用
// 引用组件,如果全局引用在index.js中全局引用插件
import WordLimitInput from 'components/WordLimitInput';
Vue.component('word-limit-input', WordLimitInput);
// 页面代码
<word-limit-input v-model="questionsData.appName" :maxlength="30"></word-limit-input>

 类似资料: