Vuejs 3 introduced composables as the new way to define logic that is shared and re-used among components. Composables were mainly introduced to solve the limitation introduced by mixins. If you are familiar with Vuejs 2 then you have heard of mixins which was the defacto standard to share and reuse code logic among components.
While mixins were great they presented some limitations such as the ones below:
- Property Source: When using numerous mixins, it can be challenging to determine which instance property originates from which mixin. This ambiguity makes it difficult to follow the component's logic. Utilizing the refs + destructure pattern with composables enhances clarity by explicitly identifying property sources.
- Namespace Collisions: Different mixins from various sources may unintentionally use the same property keys, causing conflicts. Composables offer the flexibility to rename variables when conflicts arise, sidestepping namespace collisions.
- Enhanced Modularity: Mixins can lead to implicit dependencies among multiple mixins, relying on shared property keys. Composables promote explicit communication by allowing values returned from one composable to be passed as arguments to another, fostering more modular and understandable code.
While not entirely deprecated in Vue.js 3, mixins are no longer recommended. Instead, composables are the preferred method for crafting reusable code logic.
We are going to write a simple form validation composable and see how we can re-use the logic in our components.
In this example, the
useFormValidation composable function provides the necessary variables and computed properties for form validation. This approach helps keep the component code clean…