一,什麼是Hooks?
"hooks" 直譯是 “鈎子”,它並不僅是 react,甚至不僅是前端界的專用術語,而是整個行業所熟知的用語。通常指:
系統運行到某一時刻時,會調用在該時機被註冊的回調函數
而在vue中。hooks的定義會更加模糊,姑且總結一下:
在vue組合式API中被定義為,以"use" 作為開頭的,一系列提供組件複用,狀態管理等開發能力的方法。
二,Mixin和Hooks區別
假設有個需求:
當組件實例創建時,需要創建一個
state屬性:name,並隨機給此name屬性附一個初始值。除此之外,還得提供一個setName方法。你可以在組件其他地方開銷和修改此狀態屬性。更重要的是: 這個邏輯要可以複用,在各種業務組件裏複用這個邏輯。
在擁有hooks之前,首先想到的就是Mixin
代碼如下:
// 混入文件:name-mixin.js
export default {
data() {
return {
name: 'zhng'
}
},
methods: {
setName(name) {
this.name = name
}
}
}
在組件中使用:
// 組件:my-component.vue
<template>
<div>{{ name }}</div>
<template>
<script>
import nameMixin from './name-mixin';
export default {
mixins: [nameMixin],
mounted() {
setTimeout(() => {
this.setName('Tom')
}, 3000)
}
}
<script>
由以上代碼可看出,Mixin有很大的弊端
- 會出現覆蓋,同名,名字混合
- 無法傳入參數,限制了Mixin的靈活性
- ...
hooks的用法,代碼如下:
import { computed, ref, Ref } from "vue"
// 定義hook
type CountResultProps = {
count:Ref<number>;
multiple:Ref<number>;
increase:(delta?:number)=>void;
decrease:(delta?:number)=> void;
}
export default function useCount(initValue = 1):CountResultProps{
const count = ref(initValue)
const increase = (delta?:number):void =>{
if(typeof delta !== 'undefined'){
count.value += delta
}else{
count.value += 1
}
}
const multiple = computed(()=>count.value * 2)
const decrease = (delta?:number):void=>{
if(typeof delta !== "undefined"){
count.value -= delta
}else{
count.value -= 1
}
}
return {
count,
increase,
decrease,
multiple
}
}
在組件中使用:
<template>
<p>count:{{count}}</p>
<p>倍數:{{multiple}}</p>
<div>
<button @click="increase(10)">加一</button>
<button @click="decrease(10)">減一</button>
</div>
</template>
<script setup lang="ts">
import useCount from "../views/Hook"
const {count,multiple,increase,decrease} = useCount(10)
</script>
<style>
</style>
相比之下,hooks就顯得特別好用