首页 > 其他分享 >027、Vue3+TypeScript基础,使用自定义hook,把功能计算都放到hook中精简代码

027、Vue3+TypeScript基础,使用自定义hook,把功能计算都放到hook中精简代码

时间:2024-08-18 17:04:53浏览次数:11  
标签:TypeScript 自定义 vue hook add num 10px import view

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、浏览器运行效果如下:

 

标签:TypeScript,自定义,vue,hook,add,num,10px,import,view
From: https://www.cnblogs.com/tianpan2019/p/18365804

相关文章