Vue3:自定义hooks,实现逻辑代码封装,增强代码的复用性和可维护性(axios案例演示)

一、情景说明

Vue2中,我们想要实现代码的封装与复用性,采用的技术是mixin
mixin技术案例演示:https://blog.csdn.net/Brave_heart4pzj/article/details/135483606

而在Vue3中,我们则使用hooks来实现这个效果。
什么是hook?—— 本质是一个函数,把setup函数中使用的Composition API进行了封装
我们可以用js文件或者ts文件来封装
hook的命名规范:useXxxx

二、案例

1、创建hook

useDog.ts
使用axios请求接口,获取数据,并使用了生命周期函数onMounted

import {reactive,onMounted} 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) {
      alert(error)
    }
  }
  // 钩子
  onMounted(()=>{
    getDog()
  })
  // 向外部提供东西
  return {dogList,getDog}
}

useSum.ts

import { ref ,onMounted,computed} from 'vue'

export default function () {
  // 数据
  let sum = ref(0)
  let bigSum = computed(()=>{
    return sum.value * 10
  })

  // 方法
  function add() {
    sum.value += 1
  }

  // 钩子
  onMounted(()=>{
    add()
  })

  // 给外部提供东西
  return {sum,add,bigSum}
}

2、使用hook

Person.vue
person组件中使用hook

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

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

    const {sum, add, bigSum} = 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;
    }

    li {
        font-size: 20px;
    }

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

经过案例的练习,我们可以明显的感觉到,Vue3hookVue2mixin作用非常相似
在语法上有较大差异。

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值