Introduction
In Vue.js, an input mask is a way to format and control the input of data into an input field. This can be useful for enforcing specific formats such as phone numbers, dates, or credit card numbers. directive in Vue.js is a way to directly manipulate the DOM. In this case, we'll create a directive that applies an input mask to an input field.
Here's how you can create an input mask directive step by step:
Create the Directive
const InputMaskDirective = {
bind(el, binding) {
// Retrieve the mask value from the binding object
const mask = binding.value;
// Add an input event listener to the element
el.addEventListener('input', function(e) {
// Retrieve the input value
let value = e.target.value;
// Remove non-digit characters from the input value
value = value.replace(/\D/g, '');
// Apply the mask format
let maskedValue = '';
let maskIndex = 0;
for (let i = 0; i < value.length; i++) {
// If the current character in the mask is a digit placeholder, add the next digit from the input
if (mask[maskIndex] === '#') {
maskedValue += value[i];
maskIndex++;
} else {
// If the current character in the mask is not a digit placeholder, append it to the masked value
maskedValue += mask[maskIndex];
}
// Move to the next character in the mask
maskIndex++;
}
// Update the input value with the masked value
el.value = maskedValue;
});
}
};
export default InputMaskDirective;
In this directive, we define a bind hook that is called when the directive is attached to an element. Inside the bind hook, we attach an input event listener to the element. Whenever the user types into the input field, the listener function will execute, applying the input mask to the input value.
Use the Directive in a Vue Component
<template>
<div>
<input v-input-mask="'(###) ###-####'" placeholder="Enter phone number" />
</div>
</template>
<script>
import InputMaskDirective from './InputMaskDirective';
export default {
directives: {
InputMask: InputMaskDirective
}
}
</script>
In this example, we import the InputMaskDirective and register it as a directive named v-input-mask. We then use this directive on an input field with a specified mask value of "(###) ###-####".
Add CSS Styling (Optional)
You might want to add some CSS styling to indicate the input mask to the user. For example, you could use a light gray color for the mask characters.
/* styles.css */
.input-mask {
color: #aaa;
}
Import and Use the CSS in Your Vue Component.
<style scoped>
@import './styles.css';
</style>
With this setup, the input field will display the input mask format (###) ###-####. As the user types, only the digits will be retained, and the mask characters will remain static.