SoFunction
Updated on 2025-04-04

Method of limiting length of vue bidirectional binding data by limiting data

How to limit the length of vue bidirectional binding data? Please read the article for specific methods

Problem description

In vue, the input box v-modle is two-way bound data; it needs to be limited in the required business scenarios;

Solution

The following methods can be used:

Method 1:

//Method 1: Add the keypress method in the input box; then the function is:maxLength(attr,length){
 let keyCode = ;
 ("keyCode");
  let len=0;
 (this[attr].length);
 for (let codePoint of this[attr]) {
  if (this[attr].charCodeAt(codePoint) > 128) {
    len += 2;
  } else {
   len++;
  }
  }
 if (len < length) {
   = true;
 } else {
   = false;
 }
},
//Note: The event must be keypress;//keydown Can be restricted,But the length cannot be deleted;keyupno;

Method 2:

//Method 2: Add the input method in the input box; then the function is:inputMaxLength(attr,length){
  this[attr] = (this[attr], length);
},

Method comparison:

The first advantage of the method is that there are few loops and high performance; the disadvantage is that it will not trigger when entering characters in Chinese input method in spaces;
Method 2 has advantages, good compatibility and is suitable for various scenarios; disadvantages, many cycles and poor performance;

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.