詳解hooks在vue3中的使用方法及示例
vue3 中的 hooks 是什么?
簡(jiǎn)單來(lái)說(shuō)如果你的函數(shù)中用到了諸如 ref,reactive,onMounted 等 vue 提供的 api 的話,那么它就是一個(gè) hooks 函數(shù),如果沒(méi)用到它就是一個(gè)普通工具函數(shù)。至于它為什么叫 hooks,我的理解則是
它可以通過(guò)特定的函數(shù)將邏輯 "鉤入" 組件中,使得開(kāi)發(fā)者能夠更靈活地構(gòu)建和管理組件的功能從而提高代碼的可讀性以及可維護(hù)性等
在 vue3 中使用
上面說(shuō)到 hooks 函數(shù)里包含了 vue 提供的 api,下面我們就簡(jiǎn)單的來(lái)舉個(gè)例子看一下 vue3 中的 hooks 函數(shù)。一般來(lái)說(shuō),如果一個(gè)你得函數(shù)為 hooks 函數(shù),那么你需要將其以 use 開(kāi)頭命名。在 src 下新建一個(gè) hooks 目錄專(zhuān)門(mén)存放 hooks 函數(shù),然后寫(xiě)下第一個(gè)非常簡(jiǎn)單的 hooks 函數(shù) useAdd
import { ref } from "vue";
export const useAdd = () => {
const a = ref(1);
setInterval(() => {
a.value++;
}, 1000);
return a;
};這是一個(gè)非常簡(jiǎn)單的 hooks 函數(shù),每隔一秒就讓 a.value 加 1,最后返回一個(gè)響應(yīng)式的 a,我們?cè)诮M件中引用一下
<template>
<div>{{ a }}</div>
</template>
<script lang='ts' setup>
import { useAdd } from "../hooks/useAdd"
const a = useAdd()
</script>此時(shí)我們會(huì)看到每隔一秒頁(yè)面上的值就會(huì)加 1,所以說(shuō) a 還是保持了它的響應(yīng)式特性

當(dāng)然這只是個(gè)簡(jiǎn)單的例子,后面會(huì)詳細(xì)介紹一個(gè) hooks 實(shí)際應(yīng)用的場(chǎng)景
mixin 與 hooks
我們都知道 Vue 3 引入 Composition API的寫(xiě)法,當(dāng)我們引入一個(gè) hooks 函數(shù)的時(shí)候其實(shí)就像在 vue2 中使用一個(gè) mixin 一樣,hooks 函數(shù)中的ref,reactive就相當(dāng)于 mixin 中的data,同時(shí) hooks 還可以引入一些生命周期函數(shù),watch 等在 mixin 中都有體現(xiàn)。下面展示一下 mixin 的寫(xiě)法,這里不過(guò)多的講解 mixin
export const mixins = {
data() {
return {
msg: "",
};
},
computed: {},
created() {
console.log("我是mixin中的created生命周期函數(shù)");
},
mounted() {
console.log("我是mixin中的mounted生命周期函數(shù)");
},
methods: {
clickMe() {
console.log("我是mixin中的點(diǎn)擊事件");
},
},
};組件中引入
export default {
name: "App",
mixins: [mixins],
components: {},
created() {
console.log("組件調(diào)用minxi數(shù)據(jù)", this.msg);
},
mounted() {
console.log("我是組件的mounted生命周期函數(shù)");
},
};用過(guò) vue2 的 mixin 的都知道它雖然可以封裝一些邏輯,但是它同時(shí)也帶來(lái)了一些問(wèn)題.比如你引入多個(gè) mixin 它們的 data,methods 命名可能會(huì)沖突,當(dāng) mixin 多了可能會(huì)出現(xiàn)維護(hù)性問(wèn)題,另外 mixin 不是一個(gè)函數(shù),因此不能傳遞參數(shù)來(lái)改變它的邏輯,具有一定的局限性等,但這些問(wèn)題到了 vue3 的 hooks 中則迎刃而解
hooks 中生命周期執(zhí)行順序
hooks 中生命周期與組件中的生命周期執(zhí)行順序其實(shí)很好判斷,就看它們誰(shuí)的同級(jí)生命周期函數(shù)先創(chuàng)建那就先執(zhí)行誰(shuí)的,比如在 useAdd 中加幾個(gè)生命周期
import { ref, onMounted, onBeforeUnmount, onUnmounted } from "vue";
export const useAdd = () => {
const a = ref(1);
setInterval(() => {
a.value++;
}, 1000);
onMounted(() => {
console.log("hooks---onMounted");
});
onBeforeUnmount(() => {
console.log("hooks---onMounted");
});
onUnmounted(() => {
console.log("hooks---onUnmounted");
});
return a;
};然后在組件中也引入這些生命周期
<template>
<div>{{ a }}</div>
</template>
<script lang='ts' setup>
import { useAdd } from "../hooks/useTest"
import { onMounted, onBeforeUnmount, onUnmounted } from "vue";
onMounted(() => {
console.log("組件---onMounted");
});
onBeforeUnmount(() => {
console.log("組件---onMounted");
});
onUnmounted(() => {
console.log("組件---onUnmounted");
});
const a = useAdd()
</script>如果將 hooks 放到最后那么它們的順序是這樣的

如果放到前面那就是這樣的

ok,vue3 的 hooks 就介紹這些,接下來(lái)我們寫(xiě)兩個(gè)實(shí)際應(yīng)用中的 hooks 函數(shù)讓大家體驗(yàn)一下
封裝一個(gè)發(fā)送短信驗(yàn)證碼倒計(jì)時(shí) hooks
我們先直接在組件中實(shí)現(xiàn)一個(gè)發(fā)送短信的功能,注意下面只寫(xiě)了一些主要邏輯,很多細(xì)節(jié)并未處理
<template>
<div>
<input type="text" placeholder="請(qǐng)輸入驗(yàn)證碼" v-model="code">
<button @click="sendCode">{{ sendBtnText }}</button>
</div>
</template>
<script lang='ts' setup>
import { ref } from 'vue';
const code = ref('')
const sendBtnText = ref('發(fā)送驗(yàn)證碼')
const countDownNum = ref(60)
const sendCode = () => {
//這里省略調(diào)用發(fā)送短信接口邏輯,省略禁止點(diǎn)擊邏輯
sendBtnText.value = countDownNum.value + 's'
const timer = setInterval(() => {
countDownNum.value--
sendBtnText.value = countDownNum.value + 's'
if (countDownNum.value === 0) {
clearInterval(timer)
sendBtnText.value = '發(fā)送驗(yàn)證碼'
countDownNum.value = 60
}
}, 1000)
}
</script>
<style lang="css">
button {
font-size: 14px;
background: #23A7F2;
color: #fff;
}
input {
height: 30px;
}
</style>這里邏輯很簡(jiǎn)單,就是點(diǎn)擊發(fā)送按鈕開(kāi)啟定時(shí)器出現(xiàn)倒計(jì)時(shí)的功能

假如我們還有其它地方用到發(fā)送短信頁(yè)面,我們可以將短信發(fā)送封裝成一個(gè)組件。但是如果其它頁(yè)面想要使用的發(fā)送短信頁(yè)面和這個(gè)組件不一樣的話,我們就需要將它的邏輯抽離封裝成一個(gè) hooks 函數(shù)了,下面我們就將這個(gè)倒計(jì)時(shí)功能封裝成一名為 useCountDown 的 hooks
import { Ref, ref } from "vue";
export default (
downNum: number
): ({ sendBtnText: Ref<string>, sendCode: () => void }) => {
const sendBtnText = ref("發(fā)送驗(yàn)證碼");
const countDownNum = ref(downNum);
//這里省略調(diào)用發(fā)送短信接口邏輯,省略禁止點(diǎn)擊邏輯
const sendCode = () => {
sendBtnText.value = countDownNum.value + "s";
const timer = setInterval(() => {
countDownNum.value--;
sendBtnText.value = countDownNum.value + "s";
if (countDownNum.value === 0) {
clearInterval(timer);
sendBtnText.value = "發(fā)送驗(yàn)證碼";
countDownNum.value = 60;
}
}, 1000);
};
return { sendBtnText, sendCode };
};邏輯和上面一樣,只不過(guò)是返回了一個(gè)按鈕要顯示的文本以及一個(gè)點(diǎn)擊發(fā)送驗(yàn)證碼調(diào)用的函數(shù)。然后在組件中使用
import { ref } from "vue";
import useCountDown from "../hooks/useCountDown";
const code = ref("");
const { sendBtnText, sendCode } = useCountDown(60);這樣的話在其它組件中就也能夠使用它了
寫(xiě)在最后
Vue 3中的Hooks函數(shù)是一個(gè)非常實(shí)用的功能,在組件開(kāi)發(fā)中他能夠?qū)⒁恍┩ㄓ眠壿嫵殡x實(shí)現(xiàn)邏輯的復(fù)用,大大提高了我們代碼的可讀性及可維護(hù)性。
以上就是詳解hooks在vue3中的使用方法及示例的詳細(xì)內(nèi)容,更多關(guān)于vue3中hooks使用的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Vue.extend 登錄注冊(cè)模態(tài)框的實(shí)現(xiàn)
這篇文章主要介紹了Vue.extend 登錄注冊(cè)模態(tài)框的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
關(guān)于Element-UI中slot的用法及說(shuō)明
這篇文章主要介紹了關(guān)于Element-UI中slot的用法及說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10
vue中watch監(jiān)聽(tīng)不到變化的解決
本文主要介紹了vue中watch監(jiān)聽(tīng)不到變化的解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01
vue3中g(shù)etCurrentInstance獲取組件實(shí)例踩坑詳細(xì)記錄
getCurrentInstance()是Vue.js3?Composition?API中的一個(gè)函數(shù),它的作用是獲取當(dāng)前組件的實(shí)例對(duì)象,下面這篇文章主要給大家介紹了關(guān)于vue3中g(shù)etCurrentInstance獲取組件踩坑的相關(guān)資料,需要的朋友可以參考下2024-02-02
拖拽插件sortable.js實(shí)現(xiàn)el-table表格拖拽效果
本文主要介紹了拖拽插件sortable.js實(shí)現(xiàn)el-table表格拖拽效果,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02
Vue resource中的GET與POST請(qǐng)求的實(shí)例代碼
本篇文章主要介紹了Vue resource中的GET與POST請(qǐng)求的實(shí)例代碼,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2017-07-07

