In Vue 3, the Composition API provides a new approach to organizing and reusing component logic. Compared to the previous Options API, the Composition API is more flexible and better suited for managing the state and logic of complex components. Below are the steps and examples for sharing logic between components:
Step 1: Create a Reusable Composition Function
First, create a Composition Function, which is a JavaScript function encapsulating reusable logic. This function can return reactive data, methods, or other Composition API features, such as computed properties and watch.
Example:
Suppose we have logic for handling user information; we can create a Composition Function named useUser.
javascriptimport { ref, computed } from 'vue'; export function useUser() { const users = ref([]); const addUser = (user) => { users.value.push(user); }; const userCount = computed(() => users.value.length); return { users, addUser, userCount }; }
Step 2: Use the Composition Function in Components
After creating the Composition Function, you can use it in any component to share logic.
Example:
Using useUser in two different components to manage user data.
javascript// Component A import { useUser } from './useUser'; export default { setup() { const { users, addUser, userCount } = useUser(); return { users, addUser, userCount }; } } // Component B import { useUser } from './useUser'; export default { setup() { const { users, addUser } = useUser(); const addUserFromB = (name) => { addUser({ name }); }; return { users, addUserFromB }; } }
Step 3: Maintain State Independence
Although the Composition API enables sharing logic between different components, be mindful of state independence between instances. If you need each component to maintain independent data state, ensure the Composition Function uses a function or factory pattern to return new instances.
javascriptexport function useUser() { const users = ref([]); return { users: ref([]), addUser: (user) => users.value.push(user), userCount: computed(() => users.value.length) }; }
With this pattern, each call to useUser() in a component creates a new reactive reference, ensuring data is not shared between different component instances.
Summary
Through the above steps, you can see that sharing logic using the Composition API in Vue 3 is highly flexible and powerful. It not only makes the code more modular but also improves development efficiency and maintainability. Ensure you design Composition Functions and component logic reasonably based on your application needs to maximize the advantages of this API.