Essentially, I want to build input field components (textfeids, textarea, checkbox, ...). Since they share some attributes ie (id, name,...), my approach was to create a composable and define the common prop definition and use them in the individual components. However, it seems it does not work. Is there a way I can achieve this in vue 3 composable approach? Below is the composable.
// prop definition
import { defineProps } from "vue";
export const useCoreFieldProps = () => {
const props = defineProps<{
id?: string;
name?: string;
disabled?: boolean;
required?: boolean;
}>();
return {
props,
};
};
// composable usage
<script setup lang="ts">
import { useCoreFieldProps } from "@/composables/useFields";
const { props: coreProps } = useCoreFieldProps();
</script>
Rather than calling defineProps in the composable, you can return just the object and you can call defineProps on it in your component:
// composable definition
export const useCoreFieldProps = () => {
const fieldProps = {
id?: string;
name?: string;
disabled?: boolean;
required?: boolean;
};
return {
fieldProps,
};
};
// composable usage
<script setup lang="ts">
import { useCoreFieldProps } from "@/composables/useFields";
const { fieldProps } = useCoreFieldProps();
defineProps(fieldProps);
// or add your own props or override:
defineProps({
...fieldProps,
maxLength?: string,
pattern?: string
});
</script>
You will unfortunately lose automated documentation of props if you’re using storybook or similar component library browsing tools, but hopefully they'll add support for that soon.
The other option is extends, but the docs don’t really explain how that works in Vue 3 with composition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With