Home > Software design >  How to format phone number with v-model on VueJs
How to format phone number with v-model on VueJs

Time:11-19

When the phone number is entered, I want it to appear in the input in the format (123) - 456 - 78 - 90. how can I do it?

<template>
<div v-for="about in abouts">
  <input type="text" v-model="about.phone">
  <input type="text" v-model="about.mail">
</div>
</template>

<script>
export default {
  data(){
    return{
      abouts:[{phone:'',mail:''},{phone:'',mail:''}]
    }
  }
}
</script>

CodePudding user response:

 const q = (ph) => {
  const batches = [3, 3, 2, 2];
  const template = '({0}) - {1} - {2} - {3}';
  let index = 0, summator = 0;
  let data = template;
  batches.forEach(x => {
    const part = ph.substring(summator, x   summator);
    data = data.replace(`{${index}}`, part);
    index  ;
    summator  = x;
  });
  return data;
}


abouts:[{phone:q('1234567890'),mail:''},{phone:'',mail:q('')}]

simple way, working. You can add trimming if phone number smaller than 10 digits

CodePudding user response:

I solved the problem. If you have the same problem you can use vue-mask package.

  • Related