Creating your composable (custom hook)
In many scenarios, we want to group some components’ logic into reusable code blocks for other components that share similar functionalities. In Vue 2.x, we use mixins to achieve this goal. However, mixins are not the best practical solution, and they can create code complexity due to the order of merging and invoking overlapping data and lifecycle hooks.
Starting from Vue 3.0, you can use the Composition API to divide the common data logic into small and isolated composables, using them to create a scoped data control in different components and return the created data if there is any. A composable is a regular JavaScript function that uses Composition API methods and performs data state management internally.
To get started, we create a new JavaScript (.js
) file, which exports a function acting as the composable. In the following example, we create a useMessages
composable, which returns a list of messages
and some methods to modify...