vue3-HOOKS模块化处理

vue3模块化处理

vue3版本的更新,就是能搞更好的重用机制,可以把想要得模块独立出去
eg:显示一个当前时间的工能,在多个页面需要调用的时候不用重复的调用
可以在src目录下,新建一个文件夹hooks(所有抽离出来的功能模块都可以放到这个文件夹里),
然后再新建一个文件useNowTime.js,这里使用use开头是一个使用习惯,代表是一个抽离出来的模块

import { ref } from "vue";

const nowTime = ref("00:00:00");
const getNowTime = () => {
    const now = new Date();
    const hour = now.getHours() < 10 ? "0" + now.getHours() : now.getHours();
    const minu =
        now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes();
    const sec =
        now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds();
    nowTime.value = hour + ":" + minu + ":" + sec;

    setTimeout(getNowTime, 1000);
};

export { nowTime, getNowTime }

注意:需要将定义的变量nowTime和方法getNowTime通过export导出
使用的时候跟在setup中定义的变量和方法一样使用

使用模块化封装一个远程调用接口的组件
建立useURLAxios.js文件
在文件中定义远程加载需要的 变量和axios请求

import {ref} from 'vue'
import axios from 'axios';
function usURLAxios(url) {
    const result = ref(null)
    const loading = ref(true)
    const loaded =ref(false)
    const error =ref(null)
    axios.get(url).then((res)=>{
        loading.value = false
        loaded.value = true
        result.value = res.data
    }).catch(e=>{
        error.value = e
        loading.value = false
    })
    return {
        result,
        loading,
        loaded,
        error

    }
}
export default usURLAxios

使用时
新增一个.vue文件

<template>
  <div>
    <button @click="getImg">随机展示图片</button>
    <div v-if="thisloading">Loading.....</div>
    <img v-if="thisloaded" :src="thisresult.message" />
    <div></div>
  </div>
</template>

<script>
import { reactive, toRefs } from "vue";
import useUrlAxios from "../hooks/useURLAxios";
export default {
  setup() {
    const data = reactive({
      thisresult: null,
      thisloading: true,
      thisloaded: false,
      getImg: () => {
        const { result, loading, loaded } = useUrlAxios(
          "https://dog.ceo/api/breeds/image/random"
        );
        data.thisresult = result;
        data.thisloading = loading;
        data.thisloaded = loaded;
        console.log(
          22222,
          data.thisresult,
          data.thisloading,
          data.thisloaded,
          result,
          loaded,
          loading
        );
      },
    });
    const refData = toRefs(data);

    return { ...refData };
  },
};
</script>

<style lang="scss" scoped>
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值