/
ErrorMessage.ts
58 lines (50 loc) · 1.52 KB
/
ErrorMessage.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { inject, h, defineComponent, computed, resolveDynamicComponent } from 'vue';
import { FormErrorsKey } from './symbols';
import { normalizeChildren } from './utils';
export const ErrorMessage = defineComponent({
name: 'ErrorMessage',
props: {
as: {
type: String,
default: undefined,
},
name: {
type: String,
required: true,
},
},
setup(props, ctx) {
const errors = inject(FormErrorsKey, undefined);
const message = computed<string | undefined>(() => {
return errors?.value[props.name];
});
function slotProps() {
return {
message: message.value,
};
}
return () => {
// Renders nothing if there are no messages
if (!message.value) {
return undefined;
}
const tag = (props.as ? resolveDynamicComponent(props.as) : props.as) as string;
const children = normalizeChildren(tag, ctx, slotProps);
const attrs = {
role: 'alert',
...ctx.attrs,
};
// If no tag was specified and there are children
// render the slot as is without wrapping it
if (!tag && (Array.isArray(children) || !children) && children?.length) {
return children;
}
// If no children in slot
// render whatever specified and fallback to a <span> with the message in it's contents
if ((Array.isArray(children) || !children) && !children?.length) {
return h(tag || 'span', attrs, message.value);
}
return h(tag, attrs, children);
};
},
});