hooks

自定义hooks

1、将对应一个功能的代码拆分出去:

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

//有了default后 function不用加名字
export default function () {
  //数据
  let dogList = reactive([
    "https://images.dog.ceo/breeds/papillon/n02086910_9579.jpg",
  ]);

  //方法
  async function getDog() {
    try {
      let result = await axios.get("https://dog.ceo/api/breeds/image/random");
      console.log(result.data.message);
      dogList.push(result.data.message);
    } catch (error) {
      alert(error);
    }
  }

  //挂载后
  onMounted(() => {
    getDog()
  })

  //向外部提供东西
  return { dogList, getDog };
}

2、然后在导入使用

<template>
  <div class="person">
    <h2>当前求和为:{{ sum }}</h2>
    <button @click="add">点我sum+1</button>
    <hr>
    <img v-for="(dog, index) in dogList" :key="index" :src="dog" alt="狗的照片">
    <br>
    <button @click="getDog">再来一只小狗</button>
  </div>
</template>

<script setup lang="ts" name="Person">
  import useDog from '../hooks/useDog';
  import useSum from '../hooks/useSum';

  const {sum, add} = useSum();
  const {dogList, getDog} = useDog();
</script>

<style scoped>
  .person {
    background-color: skyblue;
    box-shadow: 0 0 10px; /* 盒子阴影 */
    border-radius: 10px;
    padding: 20px;
  }

  button {
    margin: 0 5px;
  }

  img {
    width: 100px;
    margin-right: 10px;
  }
</style>
posted @ 2024-12-24 09:52  如此而已~~~  阅读(24)  评论(0)    收藏  举报
//雪花飘落效果