鍍金池/ 問(wèn)答/HTML/ vue中如何格式化輸入時(shí)input框中v-model的內(nèi)容?

vue中如何格式化輸入時(shí)input框中v-model的內(nèi)容?

我想在輸入時(shí),邊輸入邊格式化input中的內(nèi)容,如,輸入銀行卡號(hào),自動(dòng)四個(gè)數(shù)字空一個(gè)空格,方法本來(lái)已經(jīng)實(shí)現(xiàn)了,監(jiān)聽(tīng)input時(shí)間時(shí)進(jìn)行格式化,但是這樣的化傳遞給后臺(tái)的數(shù)據(jù)就變成了帶空格的數(shù)據(jù),我只想改變顯示內(nèi)容,實(shí)際保存的不變,應(yīng)該怎么辦? 看了網(wǎng)上的filter方法,發(fā)現(xiàn)放在v-model里面會(huì)報(bào)錯(cuò),也是了computer方法,也沒(méi)起作用。

<input name="bank_account" label="銀行卡號(hào)" placeholder="僅支持借記卡 將放款至此賬號(hào)" type="text" v-model="bank_account" @input="handleBankCardInput"  :maxlength="23" />
  handleBankCardInput(value) {
      this.bank_account = value.replace(/\s/g, '').replace(/(\d{4})(?=\d)/g, '$1 ')
      console.info(this.bank_account)
    },

嘗試的computer方法:

  computed: {
    bank_account: {
      get() {
        return this.bank_account.replace(/\s/g, ''())
        // return this.bank_account.replace(/\s/g, ''())
      },
      set(val) {
        this.bank_account = val.replace(/\s/g, '').replace(/(\d{4})(?=\d)/g, '$1 ')
      }
    }
  }
回答
編輯回答
編輯回答
朕略萌

v-model是語(yǔ)法糖,本質(zhì)是 v-bind 和 v-on的組合。想要實(shí)現(xiàn)顯示和提交內(nèi)容分離的話不能直接用v-model綁定的變量,其實(shí)也就是v-on 綁定的變量。這是由input標(biāo)簽特性所決定的:所見(jiàn)即所得!value的值即顯示的值,顯示的值即value的值。

解決方案:
1.后臺(tái)處理提交數(shù)據(jù),去空格
2.前端處理

附2.代碼:

<html>
<head>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
<div id="app">
    <input @input="strFormat($event.target)">
</div>
</body>
</html>
<script>
    var app = new Vue({
        el:'#app',
        data: {
            account: 0,
        },
        methods:{
            strFormat:function (target) {
                this.account = target.value.toString().replace(/\s/g, '');
                target.value = target.value.toString().replace(/(\d{4})(?=\d)/g, '$1 ');
            }
        }

    })
</script>

參考鏈接
vue.js-表單輸入綁定
vue.sync 與 v-model

2017年6月7日 22:24
編輯回答
雅痞

寫在watch里,改變自己。

2017年7月24日 22:26