vue3.0网络请求封装

https://blog.csdn.net/weixin_47347505/article/details/123390218  基础
https://mp.weixin.qq.com/s/FtgjUPmdldsUiN2t7XWRtA 封装

utils
(1)types->axios.d.ts
export type ErrorMessageMode = 'none' | 'modal' | 'message' | undefined;

export interface RequestOptions {
    // Splicing request parameters to url
    joinParamsToUrl?: boolean;
    // Format request parameter time
    formatDate?: boolean;
    // Whether to process the request result
    isTransformResponse?: boolean;
    // Whether to return native response headers
    // For example: use this attribute when you need to get the response headers
    isReturnNativeResponse?: boolean;
    // Whether to join url
    joinPrefix?: boolean;
    // Interface address, use the default apiUrl if you leave it blank
    apiUrl?: string;
    // 请求拼接路径
    urlPrefix?: string;
    // Error message prompt type
    errorMessageMode?: ErrorMessageMode;
    // Whether to add a timestamp
    joinTime?: boolean;
    ignoreCancelToken?: boolean;
    // Whether to send token in header
    withToken?: boolean;
}

export interface Result<T = unknown> {
    code: number;
    type: 'success' | 'error' | 'warning';
    message: string;
    result: T;
}

// multipart/form-data: upload file
export interface UploadFileParams {
    // Other parameters
    data?: Recordable;
    // File parameter interface field name
    name?: string;
    // file name
    file: File | Blob;
    // file name
    filename?: string;
    [key: string]: any;
}
(2) axios->config.ts
import { AxiosRequestConfig } from 'axios'
import { RequestOptions } from './types/axios'

export interface CreateAxiosOptions extends AxiosRequestConfig{
    requestOptions?:RequestOptions;
}

export function DefaultAxiosConfig (): CreateAxiosOptions {
  return {
    baseURL: process.env.VUE_APP_BASE_API,
    headers: {
      'Content-Type': 'application/json;charset=utf-8'
    },
    timeout: 30000,
    validateStatus () {
      return true
    },
    requestOptions: {
      isTransformResponse: true
    }
  }
}
(3)axios->frog-axios.ts
import axios, { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { CreateAxiosOptions } from './config'
import { RequestOptions, Result } from './types/axios'
import { cloneDeep } from 'lodash'

export class FrogAxios {
    private axiosInstance: AxiosInstance;
    private readonly options: CreateAxiosOptions;

    constructor (options:CreateAxiosOptions) {
      this.options = options
      this.axiosInstance = axios.create(options)
      this.setupInterceptors()
    }

    private setupInterceptors () {
      this.axiosInstance.interceptors.request.use((config:AxiosRequestConfig) => {
        if (this.options.requestOptions?.withToken) {
          // add token
          // config.headers!['Authorization']=''
        }
        return config
      }, (error) => {
        error.data = {}
        error.data.msg = 'Server Error'
        return Promise.resolve(error)
      })

      this.axiosInstance.interceptors.response.use((res:AxiosResponse<unknown>) => {
        if (this.options.requestOptions?.isTransformResponse) {
          return res.data
        }
        return res
      }, (error) => {
        error.data = {}
        error.data.msg = 'Server Error'
        return Promise.resolve(error)
      })
    }

    post<T = unknown> (config:AxiosRequestConfig, options?:RequestOptions):Promise<T> {
      return this.request({ ...config, method: 'POST' }, options)
    }

    request<T = unknown> (config:AxiosRequestConfig, options?:RequestOptions):Promise<T> {
      const conf: CreateAxiosOptions = cloneDeep(config)
      const { requestOptions } = this.options
      const opt:RequestOptions = Object.assign({}, requestOptions, options)
      conf.requestOptions = opt

      return new Promise((resolve, reject) => {
        this.axiosInstance
          .request<unknown, AxiosResponse<Result>>(conf)
          .then((res:AxiosResponse<Result>) => {
            resolve(res as unknown as Promise<T>)
          })
          .catch((e:Error | AxiosError) => {
            reject(e)
          })
      })
    }
}
(4)axios->index.ts
import { FrogAxios } from './frog-axios'
import { DefaultAxiosConfig } from './config'

function createFrogAxios () {
  return new FrogAxios(
    DefaultAxiosConfig()
  )
}

export const defHttp = createFrogAxios()
 
无关文件
utils=>screen-width
import { ref } from 'vue'

export const screenWidth = ref()

window.onresize = () => {
  screenWidth.value = document.body.clientWidth
}
window.onload = () => {
  screenWidth.value = document.body.clientWidth
}
一home.data.ts 

import { mockhomeTitleData } from '@/data/mock/mock.data' import { eegDisplayData, homeTitleData, vepFeatureData, eegRawData, gazeDirectionNormalizedData, gazeResponseData } from '@/data/modules/home' import { featureDataType, getFeatureData } from '@/data/api/home-api' import { vrca } from '@/protoc/processed' import { featureData, vector3 } from '@/data/modules/base' import { ref } from 'vue' import { queryParams } from '@/data/modules/request' // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export const scopeId = ref<queryParams>() export async function getEyeTrackingFeatureData (id: string): Promise<vrca.concussion.v1.IEyeTrackingFeatureData[]> { return await getFeatureData<featureData<vrca.concussion.v1.IEyeTrackingFeatureData>>({ filter: { kindEq: featureDataType.EyeTrackingFeatureData, meta: { scopeId: { eq: id } } } }).then(res => { return res.items.map(e => { return e.field }) }) } export async function getVepFeatureData (id: string): Promise<vepFeatureData[]> { return await getFeatureData<featureData<vrca.concussion.v1.IVepFeatureData>>({ filter: { kindEq: featureDataType.VepFeatureData, meta: { scopeId: { eq: id } } } }).then(res => { return res.items.map(e => { return { x: e.field.xSnr as number, y: e.field.ySnr as number } }) }) } export async function getConsussionFusionResult (id: string): Promise<vrca.concussion.v1.IConsussionFusionResult> { return await getFeatureData<featureData<vrca.concussion.v1.IConsussionFusionResult>>({ filter: { kindEq: featureDataType.ConsussionFusionResult, meta: { scopeId: { eq: id } } } }).then(res => { return res.items[0]?.field }) } export async function getEegRawData (id: string): Promise<eegDisplayData[]> { return await getFeatureData<featureData<eegRawData>>({ fields: 'field.oz.chData,field.oz.quality,timestamp', filter: { kindEq: featureDataType.EegRawSignalsData, meta: { scopeId: { eq: id } } } }).then(res => { return res.items.map(e => { return { chData: e.field.oz.chData, quality: e.field.oz.quality, timeStamp: e.timestamp as string } }) }) } export async function getGazeData (id: string): Promise<gazeDirectionNormalizedData> { return await getFeatureData<featureData<gazeResponseData>>({ filter: { kindEq: featureDataType.LeftAndRightEyeData, meta: { scopeId: { eq: id } } } }).then(res => { const tempData: gazeDirectionNormalizedData = { saccadesTest: [], fixationTest: [] } res.items.filter(e => { if (e.meta?.stage === 'SaccadesTest') { tempData.saccadesTest.push(e.field.gazeDirectionNormalized) } else { tempData.fixationTest.push(e.field.gazeDirectionNormalized) } }) return tempData }) } export function getTitleData (): homeTitleData[] { return [mockhomeTitleData, mockhomeTitleData, mockhomeTitleData] }
首页
export default defineComponent({
  components: {
    Top,
    Content
  },
  setup () {
    onMounted(() => {
      const tempId = useRoute().query as queryParams
      console.log('tempId', tempId)
      if (tempId.id !== undefined) {
        scopeId.value = tempId
      }
    })
    return {}
  }
})
2
 setup () {
    const displayData = ref<vrca.concussion.v1.IEyeTrackingFeatureData[]>()
    console.log('scopeId', scopeId)
    watch(scopeId, (val) => {
      if (val?.id === undefined) return
      getEyeTrackingFeatureData(val?.id).then(res => {
        displayData.value = res
      })
    })
    return {
      displayData
    }
  }
 

 

posted @ 2021-11-12 14:44  zjxgdq  阅读(1151)  评论(0编辑  收藏  举报