需求是實(shí)現(xiàn)一個(gè)銀行卡號的輸入框,也就是每4個(gè)號用一個(gè)空格分開。
我vue里面的代碼是這樣的
//add space and forbid char
this.$watch('source.card.input', function (newValue, oldValue) {
//avoid recursion
if(newValue.replace(/\s/g, '') == oldValue.replace(/\s/g, '')) {
return;
}
//filter char
let temp = this.source.card.input;
this.payinfo.cardNumber = temp.replace(/([^0-9]|\s)/g,'');
this.source.card.input = this.payinfo.cardNumber.replace(/(\d{4})/g,'$1 ');
console.log(this.source.card.input)
});
相當(dāng)于用watch監(jiān)聽輸入變化,這里前面我加了個(gè)判斷,因?yàn)槲視詣影衙浚磦€(gè)數(shù)字替換成4個(gè)數(shù)字加一個(gè)空格。.replace(/(\d{4})/g,'$1 '); 如果不加這個(gè)判斷會導(dǎo)致無限遞歸。
后面就沒啥好說的了,就是個(gè)正則