Skip to content

Commit

Permalink
feat: expose field API methods on refs with vue.expose closes #3443
Browse files Browse the repository at this point in the history
  • Loading branch information
logaretm committed Aug 13, 2021
1 parent d2c64a4 commit 9f96ef0
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
8 changes: 8 additions & 0 deletions packages/vee-validate/src/Field.ts
Expand Up @@ -191,6 +191,14 @@ export const Field = defineComponent({
};
}

ctx.expose({
setErrors,
setTouched,
reset: resetField,
validate: validateField,
handleChange,
});

return () => {
const tag = resolveDynamicComponent(resolveTag(props, ctx)) as string;
const children = normalizeChildren(tag, ctx, slotProps);
Expand Down
30 changes: 30 additions & 0 deletions packages/vee-validate/tests/Field.spec.ts
Expand Up @@ -1003,4 +1003,34 @@ describe('<Field />', () => {
await flushPromises();
expect((form as any).field).toBe('hello');
});

test('resets validation state using refs and exposed API', async () => {
const wrapper = mountWithHoc({
template: `
<div>
<Field name="field" ref="field" rules="required" v-slot="{ errors, field }">
<input type="text" v-bind="field">
<span id="error">{{ errors && errors[0] }}</span>
</Field>
<button @click="$refs.field.reset()">Reset</button>
</div>
`,
});

const error = wrapper.$el.querySelector('#error');
const input = wrapper.$el.querySelector('input');

expect(error.textContent).toBe('');

setValue(input, '');
await flushPromises();
expect(error.textContent).toBe(REQUIRED_MESSAGE);
setValue(input, '123');
await flushPromises();
wrapper.$el.querySelector('button').click();
await flushPromises();
expect(error.textContent).toBe('');
expect(input.value).toBe('');
});
});

0 comments on commit 9f96ef0

Please sign in to comment.