Search code examples
vuejs3composable

Can a VUE 3 composable contain more than a single exported function?


I am trying to re-write some functions as VUE Composables and it looks to me like only one exported function is available for a single 'composable.ts' file. Is that true, or is there a way to export multiple functions from a single composable?


Solution

  • The way that composables are (and should be used) is that they are a single function which encapsulates and reuses stateful logic. That being said, you could return multiple functions inside of the composable or even export multiple composables from the same file. An example:

    import { useFoo, useBar } from '...'
    
    const { doX, doY } = useFoo();
    const { doZ } = useBar();
    
    doX();
    doY();
    doZ();
    

    You can definitely use composables for code organization but bear in mind that if your code could be improved by making the composable stateless and doesn't need to be coupled with Vue after all, you are probably using it for the wrong cause. It would then (depending on the use-case) probably be better to use a helper type function instead.