vue3自定义hooks的步骤

143 阅读1分钟

自定义hooks文件的作用是为了分离组件中不同功能的代码,使组件的脚本文件结构更加清晰,便于维护,同时增加代码的复用性。虽然hooks这个名字有点抽象,其实就是js的函数封装后的导出和使用。hooks文件创建方法:

  1. 在项目src文件夹下建立hooks文件夹

image.png

  1. 在hooks中编写分离出来的js代码,文件使用use+功能名命名(使用use命名的好处是编辑器可以自动搜索hooks文件并提示)。hooks文件代码:
import axios from 'axios'
import { reactive} from 'vue'
//注意:变量和方法用function包裹,编程一个函数,同时使用export将函数暴露出去
export default function () {
    let i = reactive([])
    function getDog() {
        // 然后就可以使用axios发起HTTP请求了,比如:
        axios.get('https://dog.ceo/api/breed/pembroke/images/random')
            .then(response => {
                console.log(response.data)
                i.push(response.data.message)
                console.log(i)
            })
            .catch(error => {
                console.error(error);
            });
    }
    //注意有要返回值
    return {i,getDog}
}

  1. 在组件中引用,代码:
<template>
  <div  class="nihao">
    <button @click="getDog">获取狗的图片</button>
    <br>
    <img v-for="(d,index) in i" :key="index" :src="d" />
  </div>

  <div>其他方法</div>
  <div><button @click="add">点击增加:{{ m }}</button></div>
</template>

<script setup>

//从文件中导入,使用use命名可以自动搜索,@为src目录
import useDog from '@/hooks/useDog';
import useAdd from '@/hooks/useAdd';
//导入hooks文件,同时解构给变量和函数,最好同名,方便管理
const {i,getDog} = useDog()
const {m,add} = useAdd()
</script>

<style scoped>
.nihao{
    background-color: bisque;
    height: auto;
}
.nihao img{
  height: 200px;
  margin-right: 10px;
}
</style>