美文网首页
Vue文本框限制输入字数

Vue文本框限制输入字数

作者: HelloAndyZhang | 来源:发表于2018-08-14 11:32 被阅读0次
    • 使用watch方法
    <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>
    
    • 自定义指令
      1. 组件内注册
    <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 () {}
    });
    
    

    相关文章

      网友评论

          本文标题:Vue文本框限制输入字数

          本文链接:https://www.haomeiwen.com/subject/ziimbftx.html