Nuxt3

1.新建文件夹service/inde.ts

import { UseFetchOptions } from "nuxt/app";

type Methods = "GET" | "POST" | "DELETE" | "PUT";

const BASE_URL = "http://127.0.0.1:6789/api/";

export interface IResultData {
  code: number;
  data: T;
  msg: string;
}

class HttpRequest {
  request(
    url: string,
    method: Methods,
    data: any,
    options?: UseFetchOptions,
  ) {
    return new Promise((resolve, reject) => {
      const newOptions: UseFetchOptions = {
        baseURL: BASE_URL,
        method: method,
        ...options,
      };

      if (method === "GET" || method === "DELETE") {
        newOptions.params = data;
      }
      if (method === "POST" || method === "PUT") {
        newOptions.body = data;
      }

      useFetch(url, newOptions)
        .then((res) => {
          resolve(res);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 封装常用方法

  get(url: string, params?: any, options?: UseFetchOptions) {
    return this.request(url, "GET", params, options);
  }

  post(url: string, data: any, options?: UseFetchOptions) {
    return this.request(url, "POST", data, options);
  }

  Put(url: string, data: any, options?: UseFetchOptions) {
    return this.request(url, "PUT", data, options);
  }

  Delete(url: string, params: any, options?: UseFetchOptions) {
    return this.request(url, "DELETE", params, options);
  }
}

const httpRequest = new HttpRequest();

export default httpRequest;

2.使用配置文件新建请求 新建文件api/index.ts 

import httpRequest from "../service/index";

const getDepartmentList = () => {

    return httpRequest.get('getDepartmentList',"");

};

const loginApi=(data:any)=>{

  return httpRequest.post('login',data)

}

export {

    getDepartmentList,

    loginApi

};

3.在页面中使用

 

const getList = async () => {

  const res: any = await getDepartmentList();

  console.log("结果", res.data.value.departmentList[0].departmentName);

  results.value = res.data.value.departmentList[0].departmentName;

};

你可能感兴趣的:(nuxt,前端,nuxt)