vue自己写一个el-input组件的show-word-limit指令

最近接手一个很老的项目,elementUI的版本用的还是1.4的版本,好多组件的功能都用不了。

elementUI2.8.2版本以下是不支持show-word-limit这个指令的,所以用低版本的只能自己实现这个指令,实现步骤放在下面了,有需要的可以直接拿去用

先在main.js同级建立一个showWordLimit.directive.js文件,文件内容如下:

const showWordLimit = {
    bind: function (el, binding) {
        const input = el.children[0];
        const  maxlength  = input.getAttribute('maxlength');
        if (!input || !maxlength) return;
        input.style.position = 'relative';
     
        // 初始化计数器
        let counter = 0;
        
     
        // 初始化显示限制的元素
        const wordLimit = document.createElement('span');
        wordLimit.style.cssText = 'position: absolute;bottom:0;right:0; color: grey;';
     
        // 更新计数器并显示
        function updateCounter() {
          counter = input.value.length;
          wordLimit.textContent = `${counter}/${maxlength}`;
        }
        updateCounter();
     
        // 绑定输入事件监听器
        input.addEventListener('input', updateCounter, false);
     
        // 插入限制显示元素
        el.appendChild(wordLimit);
    },
};
export default showWordLimit;


然后在main.js中引入并注入全局

// main.js
import Vue form 'vue';
import showWordLimit from './showWordLimit.directive.js';
...

Vue.directive('showWordLimit ', showWordLimit);
...

然后就可以直接使用了

// xxx.vue
    <el-input
              v-model="content"
              placeholder="请填写"
               clearable :rows="4"
              type="textarea"  maxlength="30"
              v-show-word-limit   //使用的时候注意一下要用v-show-word-limit
              class="input">
          </el-input>

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值