To achieve logic reusability, you can follow these steps:
-
Creating Composable Functions (composables): You can create a standalone JavaScript function that leverages Composition API's reactive APIs such as
ref,reactive,computed,watch, andwatchEffectto create and manage state or logic. -
Using Composable Functions in Components: Within the
setupfunction of a Vue component, you can import and use these composable functions. This allows you to share and reuse the same logic across multiple components without duplicating code. -
Passing Parameters and Return Values: Composable functions can accept parameters and return reactive references, methods, or other values, enabling them to interact with components and adapt based on component requirements.
Below, I'll illustrate this process with a simple example:
Suppose we have a logic for handling user information that needs to be reused across multiple components. We can create a composable function named useUser to encapsulate this logic.
javascript// useUser.js import { ref } from 'vue'; export function useUser() { const user = ref(null); const isLoading = ref(false); async function loadUser(userId) { isLoading.value = true; try { const response = await fetch(`/api/users/${userId}`); user.value = await response.json(); } catch (error) { console.error('Failed to load user', error); } finally { isLoading.value = false; } } return { user, isLoading, loadUser }; }
In the above example, the useUser function creates a reactive reference for user information (user) and a reactive reference for the loading state (isLoading). It also provides an asynchronous function loadUser to load user data.
Now, we can use this composable function in a component:
javascript// UserProfile.vue <template> <!-- Use user and isLoading to render UI --> </template> <script> import { onMounted } from 'vue'; import { useUser } from './useUser'; export default { setup() { const { user, isLoading, loadUser } = useUser(); onMounted(() => { loadUser('123'); // Assume '123' is the user ID }); return { user, isLoading }; } }; </script>
In the setup function of the UserProfile.vue component, we import and call the useUser composable function, and invoke the loadUser function to load user data when the component is mounted. This allows user and isLoading to be directly used in the component's template.
This approach not only makes the code clearer and more maintainable but also enhances code reusability. By doing so, we can extract logic and share it across multiple components.