Hooks

什么是hook:本质是一个函数,把setup函数中使用的Composition API进行了封装,类似于vue2.x中的mixin

自定义hook的优势:复用代码, 让setup中的逻辑更清楚易懂。

未使用自定义Hooks的代码

1<template>
2  <button @click="getDogs">获取狗狗图片</button>
3  <br/>
4  <img v-for="(dog,index) in dogLists" :key="index" :src="dog" alt=""/>
5</template>
6
7<script lang="ts" name="ParentComp" setup>
8import axios from "axios";
9import {reactive} from "vue";
10
11let dogLists = reactive([])
12const getDogs = async () => {
13  let res = await axios.get("https://dog.ceo/api/breed/hound/afghan/images/random")
14  dogLists.push(res?.data?.message)
15};
16</script>
17
18<style>
19img {
20  height: 100px;
21}
22</style>

使用自定义Hooks后的代码

1<template>
2  <button @click="getDogs">获取狗狗图片</button>
3  <br/>
4  <img v-for="(dog,index) in dogLists" :key="index" :src="dog" alt=""/>
5</template>
6
7<script lang="ts" name="ParentComp" setup>
8import useDog from "@/hooks/useDog";
9
10const {dogLists, getDogs} = useDog()
11</script>
12
13<style>
14img {
15  height: 100px;
16}
17</style>
1import axios from "axios";
2import {onMounted, reactive} from "vue";
3
4export default function () {
5    // 数据
6    let dogLists = reactive([])
7    // 方法
8    const getDogs = async () => {
9        let res = await axios.get("https://dog.ceo/api/breed/hound/afghan/images/random")
10        dogLists.push(res?.data?.message)
11    };
12    onMounted(() => {
13        getDogs()
14    })
15    // 向外部提供东西
16    return {
17        dogLists,
18        getDogs
19    }
20}

:::