
import { ref } from 'vue';

export const useRequest = (apiFn, options = {}) => {
  const data = ref(null);
  const loading = ref(false);
  const error = ref(null);
  
  // 执行请求
  const execute = async (params = {}) => {
    loading.value = true;
    error.value = null;
    
    try {
      const result = await apiFn(params);
      data.value = result;
      return result;
    } catch (err) {
      error.value = err;
      throw err;
    } finally {
      loading.value = false;
    }
  };
  
  // 立即执行请求
  if (options.immediate !== false) {
    execute(options.initialParams || {});
  }
   const refresh = (newParams) => {
    return execute(newParams || options.initialParams || {});
  };
  
  return {
    data,
    loading,
    error,
    execute,
    // 重新请求
    refresh,
  };
};