Vue2 Starter
ES6 + Vue.js jsFiddle Starter Template by Christian Gambardella http://gambardella.info/2016/11/03/jsfiddle-starter-for-vue-js/
by AlexLvovsky
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.2.3/css/bulma.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.js"></script>
<div id="app" style="overflow: scroll">
<input v-mask="'##-##'" v-model="maskedValue" />
</div>
Babel + JSX
new Vue({
data() {
return {
maskedValue: '',
};
},
directives: {
mask: {
// Directive definition
bind(el, binding) {
// Define the mask pattern (e.g., '##-##')
const maskPattern = binding.value;
// Create a function to apply the mask to the input value
function applyMask(value) {
// Remove any non-digit characters from the input value
const cleanedValue = value.replace(/\D/g, '');
// Initialize variables for the masked value and pattern index
let maskedValue = '';
let patternIndex = 0;
// Loop through each character in the mask pattern
for (let i = 0; i < maskPattern.length; i++) {
const maskChar = maskPattern[i];
// If the pattern character is a '#', replace it with the next digit from the cleaned value
if (maskChar === '#') {
maskedValue += cleanedValue[patternIndex] || '_'; // Use '_' for unfilled digits
patternIndex++;
} else {
// If the pattern character is not '#', add it as is to the masked value
maskedValue += maskChar;
}
}
// Update the input element's value with the masked value
el.value = maskedValue;
}
// Apply the mask when the input element is initially bound
applyMask(el.value);
// Add an input event listener to continuously update the masked value as the user types
el.addEventListener('input', function () {
applyMask(el.value);
});
},
}
}
}).$mount('#app')