Skip to content
This repository has been archived by the owner on Sep 4, 2024. It is now read-only.

Commit

Permalink
[#511]
Browse files Browse the repository at this point in the history
* now directive will compare previous mask result with the current one if the binding value is a function when triggering update
* `input` event will not fire if calculated masked value is the same as the value of the input
  • Loading branch information
zaalbarxx committed Jan 25, 2021
1 parent 5f1490b commit 284fa37
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
11 changes: 11 additions & 0 deletions src/__tests__/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,17 @@ describe('directive usage', () => {
await wrapper.vm.$nextTick();
expect(wrapper.vm.$el.value).toBe('19:32');
});

it('should not trigger input events if resolved mask is the same as previous one', async () => {
const wrapper = mountWithMask({
props: { triggerUpdate: { required: false } },
data: () => ({ mask: () => [/\d/, /\d/], value: null }),
template: '<input v-mask="mask" v-model="value" v-on:input="$emit(\'input\', $event)" />',
});

await wrapper.setProps({ triggerUpdate: true });
expect(wrapper.emitted().input).toBeFalsy();
});
});

describe('filter usage', () => {
Expand Down
24 changes: 22 additions & 2 deletions src/directive.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ function updateValue(el, force = false) {

if ((force || isUpdateNeeded) && mask) {
const { conformedValue } = conformToMask(value, mask, { guide: false });

if (conformedValue === value) {
return;
}

el.value = conformedValue;
triggerInputUpdate(el);
}
Expand Down Expand Up @@ -95,6 +100,22 @@ function maskToString(mask) {
return filteredMaskArray.toString();
}

/**
* Check if previous mask has been different than current one
* @param {String|Array.<String|RegExp>} mask
*/
function hasMaskFromBindingChanged(el, oldValue, currentValue) {
const previousMask = isFunction(oldValue)
? maskToString(oldValue(options.get(el).previousValue))
: maskToString(oldValue);

const currentMask = isFunction(currentValue)
? maskToString(currentValue(el.value))
: maskToString(currentValue);

return previousMask !== currentMask;
}

/**
* Create the Vue directive
* @param {Object} directiveOptions
Expand Down Expand Up @@ -139,8 +160,7 @@ export function createDirective(directiveOptions = {}) {
componentUpdated(el, { value, oldValue }) {
el = queryInputElementInside(el);

const isMaskChanged = isFunction(value)
|| maskToString(oldValue) !== maskToString(value);
const isMaskChanged = hasMaskFromBindingChanged(el, oldValue, value);

if (isMaskChanged) {
updateMask(el, value, instanceMaskReplacers);
Expand Down

0 comments on commit 284fa37

Please sign in to comment.