el-input为number类型做输入长度限制

本来我想偷个懒,百度复制一下,发现热门那几个文章真的瞎掰

那我直接代码了,估计有和我一样懒的想复制就能用的

<el-input
          prefix-icon="el-icon-mobile"
          placeholder="请输入手机号"
          @input="limitPhoneNum"
          type="number"
          v-model="codeForm.phoneNum"
          autocomplete="off"
></el-input>
....
 limitPhoneNum(value) {
   if (value.toString().length > 11) {
     this.codeForm.phoneNum = this.codeForm.phoneNum.toString().slice(0, 11)
   }
   console.log(value);
    },

经过评论@love明镜的补充:

type给予number类型后依然可以输入‘+ - e’字符,所以需要更准确的进行拦截
所以新增了keydown的监听,在这里感谢@love明镜的补充

<el-input
          prefix-icon="el-icon-mobile"
          placeholder="请输入手机号"
          @input="limitPhoneNum"
          @keydown.native="inputKeyDown"
          type="number"
          v-model="codeForm.phoneNum"
          autocomplete="off"
></el-input>
....
	 limitPhoneNum(value) {
	   if (value.toString().length > 11) {
	     this.codeForm.phoneNum = this.codeForm.phoneNum.toString().slice(0, 11)
	   }
	   console.log(value);
     },
     inputKeyDown(event) {
      console.log('event', event);
      const { key } = event;
      const filterValue = ['e', '+', '-', '.'];
      if (filterValue.includes(key)) {
        event.returnValue = false;
        return false;
      }
      return true;
     },

你可能感兴趣的:(Vue,Js基础知识,vue)