027、Vue3+TypeScript基礎,使用自定義hook,把功能計算都放到hook中精簡程式碼

像一棵海草海草海草發表於2024-08-18

01、在view中建立myhook資料夾,並建立2個檔案。usesDog.ts程式碼如下:

import {onMounted, reactive} from "vue";
import axios from "axios";

export default function () {
    // 抓取圖片
    let dogList = reactive([
        'https://images.dog.ceo/breeds/pembroke/n02113023_4373.jpg'
    ])

    // 非同步函式
    async function getDog() {
        try {
            let result = await
                axios.get(
                    'https://dog.ceo/api/breed/pembroke/images/random'
                )
            dogList.push(result.data.message)
        } catch (error) {
            console.log(error)
        }
    }

    //鉤子
    onMounted(() => {
            getDog()
        }
    )
    //給外部提供
    return {dogList, getDog}
}

02、usesSum.ts程式碼如下:

import {computed, onMounted, ref} from "vue";

export default function () {
    let num = ref(0);
    let bigNum =
        computed(() => num.value * 2)

    function add() {
        num.value += 1;
    }

    //鉤子
    onMounted(() => {
            add()
        }
    )
    //給外部提供
    return {num, bigNum, add}
}

03、介面如下:

04、App.vue程式碼如下:

<template>
  <div class="app">
    <h2>App.Vue</h2>
    <Person/>
  </div>
</template>

<script lang="ts" setup name="App">
// JS或TS
import Person from './view/Person.vue';
</script>

<style scoped>
.app {
  background-color: #ddd;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;
}
</style>

05、Person.vue程式碼如下:

<template>
  <div class="person">
    <h2>當前數值為:{{ num }}, 兩倍為:{{ bigNum }}</h2>
    <button @click="add">點我+1</button>
    <hr>
    <img v-for="(dog,index) in dogList" :src="dog" :key="index"><br>
    <button @click="getDog">獲取小狗</button>
  </div>
</template>

<script lang="ts" name="Person001" setup>
import useDog from "@/view/myhook/useDog";
import useSum from "@/view/myhook/usesSum";

const {num, bigNum, add} = useSum();
const {dogList, getDog} = useDog();

</script>
<style scoped>
.person {
  background-color: #ddd;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;

  button {
    margin: 0 5px;
  }

  img {
    max-width: 100px;
    height: 100px;
    margin: 10px;
  }
}
</style>

06、效果如下:

07、瀏覽器執行效果如下:

相關文章