vue 中實現功能復用的方法有兩種:自定義 hook: 1. 創建以 use 開頭的 javascript 函數;2. 在組件中導入并調用 hook。組合式 api: 1. 使用 ref 創建反應式值;2. 使用函數組合反應式值和函數;3. 在組件中導入和使用組合式 api。
Vue 中 Hooks 實現功能復用的方法
Hooks 是 Vue 3.0 中引入的一種功能強大的機制,允許我們在不修改組件定義的情況下重用邏輯。它為功能復用提供了簡潔且靈活的方法。
使用自定義 Hook
自定義 Hook 是一種創建可重用功能的常見方法。它們是普通 JavaScript 函數,以 use 前綴開頭。
<code class="javascript">import { ref, watch } from '<a style="color:#f60; text-decoration:underline;" href="https://www.php.cn/zt/15721.html" target="_blank">vue</a>'
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>
登錄后復制
然后,可以在任何組件中使用此自定義 Hook:
<code class="javascript"><template><div>
<button>+</button>
<button>-</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>
登錄后復制
利用組合式 API
Vue 3.0 引入了組合式 API,它提供了一組函數,用于創建和組合反應式值和函數。這允許我們輕松地創建可重用的功能。
例如,以下代碼創建了一個 useInput Hook,用于管理表單輸入:
<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>
登錄后復制
在組件中,可以使用它來創建可重用的輸入字段:
<code class="javascript"><template><input v-model="input.value"></template><script>
import { useInput } from './useInput'
export default {
setup() {
const input = useInput('')
return { input }
},
}
</script></code>
登錄后復制
結論
通過自定義 Hook 和組合式 API,我們可以輕松地在 Vue 中實現功能復用,從而使我們的代碼更具模塊化、可維護性和可重用性。






