Categories
JavaScript Vue

Creating Masked Input in a Vue App with v-mask

Spread the love

We can use the v-mask package to add masked inputs into our Vue component.

To install it, we run:

npm install v-mask

Then we can use it by registering the plugin in main.js:

import Vue from "vue";
import App from "./App.vue";
import VueMask from "v-mask";
Vue.use(VueMask);

Vue.config.productionTip = false;

new Vue({
  render: h => h(App)
}).$mount("#app");

We called Vue.use(VueMask); to register the plugin globally.

Then we can add a mask to a component by writing:

<template>
  <div id="app">
    <input type="text" v-mask="'###-###-####'" v-model="phone">
    <p>{{phone}}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      phone: ""
    };
  }
};
</script>

The v-mask directive is available after we registered the plugin/

We pass in a string with the phone number mask.

Now the input can only take phone numbers.

Also, we have v-model to bind the inputted value into a state.

Now when we type in a phone number, we’ll see it reflect in the p element below.

We can also use it as a filter.

If we have:

<template>
  <div id="app">
    <p>{{phone | VMask('(###) ###-####')}}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      phone: "1234567890"
    };
  }
};
</script>

Then the value of phone will be displayed as a phone number.

We just pass in the mask format into the VMask filter to display the string our way.

v-mask is an easy to use plugin to let us add input masks into a Vue app.

It can also be used as a filter.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.