Vue文本框限制输入字数

2018-08-14  本文已影响0人  HelloAndyZhang
<template>
  <div class="box">
        <textarea  v-model="title" width="100%" ></textarea>
         <span>还可以输入{{this.titleMaxLength - this.title.length}}</span>
  </div>
</template>
<script>
export default {
  name: 'Box',
    data() {
        return {
            title: '',
            titleMaxLength: 60
        };
    },
    methods:{
    },
    watch: {
        title() {
            if (this.title.length > this.titleMaxLength) {
                this.title = String(this.title).slice(0, this.titleMaxLength);
            }
        }
    }
}
</script>
<style lang="less">
.box{
    width: 100%;
    textarea{
        width: 100%;
        height: 60px;
        border: none;
        outline: none;
        box-sizing: border-box;
    }
}
</style>
<template>
  <div class="box">
        <textarea v-sliceString="titleMaxLength" v-model="title" width="100%" ></textarea>
        <span>还可以输入{{this.titleMaxLength - this.title.length >= 0 ?this.titleMaxLength - this.title.length : 0 }}</span>
  </div>
</template>
<script>
export default {
  name: 'Box',
    data() {
        return {
            title: '',
            titleMaxLength: 10,
        };
    },
    methods:{
    },
    directives: {
        sliceString: {
            update(el, binding) {
                if (el.value.length >= binding.value) {
                    el.value = el.value.slice(0, binding.value);
                }
            }
        }
    }
}
</script>
<style lang="less">
.box{
    width: 100%;
    textarea{
        width: 100%;
        height: 60px;
        border: none;
        outline: none;
        box-sizing: border-box;
    }
}
</style>

全局注册


// man.js

Vue.directive('limitTextLen', {
    bind: function () {},
    inserted: function () {},
    update: function (el, binding) {
        if (el.value.length >= binding.value) {
            el.value = el.value.slice(0, binding.value);
        }      
    },
    componentUpdated: function () {},
    unbind: function () {}
});

上一篇下一篇

猜你喜欢

热点阅读