最近接手一个很老的项目,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>