diff --git a/src/FormularioInput.vue b/src/FormularioInput.vue index 1b993b3..ad70f1b 100644 --- a/src/FormularioInput.vue +++ b/src/FormularioInput.vue @@ -57,6 +57,9 @@ export default class FormularioInput extends Vue { // Affects only observing & setting of local errors @Prop({ default: false }) errorsDisabled!: boolean + @Prop({ default: () => value => value }) modelGetConverter!: Function + @Prop({ default: () => value => value }) modelSetConverter!: Function + public proxy: any = this.getInitialValue() private localErrors: string[] = [] @@ -69,10 +72,12 @@ export default class FormularioInput extends Vue { get model (): any { const model = this.hasModel ? 'value' : 'proxy' - return this[model] !== undefined ? this[model] : '' + return this.modelGetConverter(this[model]) } set model (value: any) { + value = this.modelSetConverter(value, this.proxy) + if (!shallowEqualObjects(value, this.proxy)) { this.proxy = value } diff --git a/test/unit/FormularioInput.test.js b/test/unit/FormularioInput.test.js index 9f732fc..50ca524 100644 --- a/test/unit/FormularioInput.test.js +++ b/test/unit/FormularioInput.test.js @@ -275,4 +275,76 @@ describe('FormularioInput', () => { expect(wrapper.find('span').exists()).toBe(true) }) + + it('Model getter for input', async () => { + const wrapper = mount({ + data: () => ({ values: { test: 'abcd' } }), + template: ` + + + {{ context.model }} + + + `, + methods: { + onGet(source) { + if (!(source instanceof Date)) { + return 'invalid date' + } + + return source.getDate() + } + } + }) + + await flushPromises() + expect(wrapper.find('span').text()).toBe('invalid date') + + wrapper.vm.values = { test: new Date('1995-12-17') } + await flushPromises() + expect(wrapper.find('span').text()).toBe('17') + }) + + it('Model setter for input', async () => { + const wrapper = mount({ + data: () => ({ values: { test: 'abcd' } }), + template: ` + + + + + + `, + methods: { + onGet(source) { + if (!(source instanceof Date)) { + return source + } + + return source.getDate() + }, + onSet(source) { + if (source instanceof Date) { + return source + } + if (isNaN(source)) { + return undefined + } + + let result = new Date('2001-05-01') + result.setDate(source) + + return result + } + } + }) + + await flushPromises() + expect(wrapper.vm.values.test).toBe(undefined) + + wrapper.find('input[type="text"]').element['value'] = '12' + wrapper.find('input[type="text"]').trigger('input') + await flushPromises() + expect(wrapper.vm.values.test.toISOString()).toBe((new Date('2001-05-12')).toISOString()) + }) })