There are two ways to implement function reuse in Vue: Custom Hook: 1. Create a JavaScript function starting with use; 2. Import and call Hook in the component. Composition API: 1. Use ref to create reactive values; 2. Use functions to combine reactive values and functions; 3. Import and use the composition API in components.
How Hooks in Vue implements function reuse
Hooks is a powerful function introduced in Vue 3.0 Mechanism that allows us to reuse logic without modifying component definitions. It provides a concise and flexible method for functional reuse.
Using Custom Hooks
Custom Hooks are a common way to create reusable functionality. They are normal JavaScript functions, starting with the use
prefix.
<code class="javascript">import { ref, watch } from 'vue' export const useCounter = () => { const count = ref(0) watch(count, (newValue) => { console.log(`Count changed to: ${newValue}`) }) return { count, increment: () => count.value++, decrement: () => count.value--, } }</code>
This custom Hook can then be used in any component:
<code class="javascript"><template> <div> <button @click="increment">+</button> <button @click="decrement">-</button> <p>Count: {{ count }}</p> </div> </template> <script> import { useCounter } from './useCounter' export default { setup() { const { count, increment, decrement } = useCounter() return { count, increment, decrement } }, } </script></code>
Leveraging the Compositional API
Vue 3.0 introduces the Compositional API , which provides a set of functions for creating and combining reactive values and functions. This allows us to easily create reusable functionality.
For example, the following code creates a useInput
Hook for managing form input:
<code class="javascript">import { ref } from 'vue' export const useInput = (initialValue) => { const value = ref(initialValue) const updateValue = (newValue) => { value.value = newValue } return { value, updateValue, } }</code>
In a component, you can use this to create reusable input fields:
<code class="javascript"><template> <input v-model="input.value" @input="input.updateValue" /> </template> <script> import { useInput } from './useInput' export default { setup() { const input = useInput('') return { input } }, } </script></code>
Conclusion
Through custom Hooks and combined APIs, we can easily implement function reuse in Vue, thus making our code more modular , maintainability and reusability.
The above is the detailed content of How to implement functional reuse with hooks in vue. For more information, please follow other related articles on the PHP Chinese website!