vue处理异步状态的逻辑useAsyncState

useAsyncState并不是Vue.js的原生API,而是一些第三方库提供的自定义hook,用于简化在Vue组件中处理异步操作的过程,如发送网络请求、加载数据或执行其他耗时的任务。

实现

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

/**
 * useAsync
 * @param  {Promise} pro 异步操作
 * @param  {Object} options 参数
 * @param  {Boolean} [options.manual=false] 是否手动调用
 * @param  {Any} options.initialData 初始化数据
 * @param  {Function} options.onSuccess 成功回调
 * @param  {Function} options.onError 失败回调
 */

export function useAsync(pro, options = {}) {
  const {
    manual = false,
    initialData,
    onSuccess = () => {}, 
    onError = console.log,
  } = options;

  const state = reactive({
    data: initialData || null,
    error: null,
    loading: false,
  });

  const run = async () => {
    state.error = null;
    state.loading = true;
    try {
      const result = await pro();
      state.data = result;
      onSuccess();
    } catch (err) {
      onError(err);
      state.error = err;
    } finally {
      state.loading = false;
    }
  };

  onMounted(() => {
    !manual && run();
  });

  // 从外部主动改变数据
  function mutate(data) {
    state.data = data;
  }
  return {
    ...toRefs(state),
    run,
    mutate,
  };
}

使用

<template>
    <div v-if="listLoading">Loading...</div>
    <div v-else-if="state">Data: {{ state }}</div>
    <button @click="getList">run</button>
  </div>
</template>
<script setup>
const {
    data: listData,
    loading: listLoading,
    run: getList,
} = useAsync(() => API.getList({
    flag: 1,
    pageNo: 0,
    pageSize: 20,
}), { initialData: {}, manual: true });
</script>

相关推荐

  1. vue处理异步状态逻辑useAsyncState

    2024-04-20 22:36:05       19 阅读
  2. 如何在SQL中优雅地处理发货状态逻辑

    2024-04-20 22:36:05       19 阅读
  3. Vue状态管理Vux

    2024-04-20 22:36:05       37 阅读
  4. vue异步更新 $nextTick

    2024-04-20 22:36:05       34 阅读
  5. VuexVue.js 状态管理库

    2024-04-20 22:36:05       11 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-20 22:36:05       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-20 22:36:05       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-20 22:36:05       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-20 22:36:05       20 阅读

热门阅读

  1. Spring Cloud Gateway面试题

    2024-04-20 22:36:05       53 阅读
  2. Ubuntu如何给tar.gz文件创建桌面快捷方式

    2024-04-20 22:36:05       51 阅读
  3. 力扣经典150题第三十三题:最小覆盖子串

    2024-04-20 22:36:05       19 阅读
  4. 多数元素(C++)

    2024-04-20 22:36:05       13 阅读
  5. SpringMVC接收参数方式讲解

    2024-04-20 22:36:05       16 阅读