vue.jsvuejs3composable

Composables advantages and vs global functions


I am in the process of understanding the concept of Vue composables. The programmatic advantages quickly become clear. But to be honest, I'm wondering why the composables functions are not stored globally once? Similar to VueX Store. A composable is imported everywhere in the components where it is needed. Wouldn't it be easier to have the interface to the functions globally? Wouldn't that save the step of importing? The only thing that could speak against it would be the clarity. But even this could be structured. Or am I still getting it wrong?


Solution

  • Besides what wrote Peter Pointer in the comments, there's some important feature as tree-shaking.

    When you import a composable into a component, when the component isn't used it won't be added to the final build TOGETHER with the composable. That's called tree-shaking and allows to remove all unused code in the final build. You want your JS build to be as small and fast as possible, right?

    There's no need to import anything in your code, just use an auto import plugin like

    https://github.com/unplugin/unplugin-auto-import

    And of course when you import you can use composables with the same name from different packages. That solves the old namespacing problem. Importing is invented for a reason.