Defining props inside composables #7463
-
Hello Vue people I have to ask this here, since google seems to only give me some questionabe workarounds and the docs don't say much about this. I was wondering whether (and how) someone could define a new prop within a composable. Meaning that, with using said composable, the component using it may gain one or more props. I know we cannot use Pseudo-code function useFoobar() {
const myprops = addProps({ foo: String })
// do something with the 'foo' prop
} <script setup>
// in some component
useFoobar()
// ...
</script> <template>
<some-component foo="I exist now" />
</template> I was simply confused to not find any clear explanation in the docs either how this may be possible, or why it can't. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
You can't. Composables are meant to be re-usable, so they should not be tied to specific props. What you can do is provide props definitions alongside your composable: export const FoobarProps = {
{ foo: String }
}
function useFoobar(props) {
props.foo
} The advantage of this, in terms of reusability, is that the consumer can choose to actually declare these props and pass the props to the composable, or choose to pass other data into the composable that has the required interface shape. |
Beta Was this translation helpful? Give feedback.
-
In some scenarios, multiple SFCs may have the same props definition. In Vue 2, this can be resolved using mixins, but in Vue 3, it needs to be redefined in each SFC file, which clearly adds complexity and makes props maintenance more cumbersome. Therefore, unifying property definitions in composables becomes a viable option. |
Beta Was this translation helpful? Give feedback.
You can't. Composables are meant to be re-usable, so they should not be tied to specific props.
What you can do is provide props definitions alongside your composable:
The advantage of this, in terms of reusability, is that the consumer can choose to actually declare these props and pass the props to the composable, or choose to pass other data into the composable that has the required interface shape.