使用class二次封装axios

29 篇文章 0 订阅

使用class 二次封装 axios, 方便后续直接调用 get 方法或 post 方法,当有多个 baseURL  的时候,还可以创建多个实例使用,简直太方便用了。

安装 axios

npm i axios -S

目录

        1. request 文件夹里面 index.js 是封装的axios,config.js 存放baseURL。

        2. modules 文件夹里,存放不同模块的 api 接口。

        3. services 下的 index.js 负责把 module 下的所有 api 一次性导出。

 

1. 新建services/request/config.js 存放 BASE_URL

export const BASE_URL = 'http://xxx.xxx.xx.xx:xxx/api'
// export const BASE_URL = 'http://xxxxxx.com:xxx/api'
export const TIMEOUT = 10000

 2. 新建services/request/index.js 二次封装axios

import axios from 'axios'
import { BASE_URL, TIMEOUT } from './confnig'
import { useMainStore } from '@/stores/modules/main'

const mainStore = useMainStore()

class myRequest {
  constructor(baseURL, timeout = 10000) {
    this.instance = axios.create({
      baseURL,
      timeout
    })
    //  请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
        // 在发送请求前显示正在加载
        mainStore.isLoading = true
        return config
      },
      (err) => {
        return err
      }
    )

    // 响应拦截器
    this.instance.interceptors.response.use(
      (res) => {
        // 拿到响应数据后,关闭加载中的显示
        mainStore.isLoading = false
        return res
      },
      (err) => {
        mainStore.isLoading = false
        return err
      }
    )
  }

  request(config) {
    return new Promise((resolve, reject) => {
      this.instance
        .request(config)
        .then((res) => {
          resolve(res.data)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  get(config) {
    return this.instance({ ...config, method: 'get' })
  }

  post(config) {
    return this.instance({ ...config, method: 'post' })
  }
}

export default new myRequest(BASE_URL, TIMEOUT)

3. 新建services/modules/city.js  封装接口

import myRequest from '../request/index'

// 1.获取定位城市
export function getCityAll() {
  return myRequest.get({
    url: '/city/all'
  })
}

services/modules/detail.js 

import myRequest from '../request/index'

// 获取房屋详细信息
export function getDetailInfos(houseId) {
  return myRequest.get({
    url: '/detail/infos',
    params: {
      houseId
    }
  })
}

4.新建services/index.js 全部导出使用

export * from './modules/city'
export * from './modules/home'
export * from './modules/detail'

5. 直接使用

import { getDetailInfos } from '@/services/index'


// 发送网络请求 获取房屋数据
const detailInfos = ref({})

// 使用计算属性,可选链操作符获取 mainPart的内容
const mainPart = computed(() => detailInfos?.value.mainPart)

getDetailInfos(houseId).then((res) => {
  // console.log(res.data.data)
  detailInfos.value = res.data.data
})

6.如果需要数据共享,可以在 stores 中的 actions 里使用

stores/modules/city.js

import { defineStore } from 'pinia'
import { getCityAll } from '@/services'

const useCityStore = defineStore('city', {
  state: () => ({
    allCities: {},

    currentCity: {
      cityName: '广州'
    } // 选中的城市
  }),
  actions: {
    // 获取所有城市数据
    async fetchAllCitiesData() {
      const res = await getCityAll()
      // console.log(res)
      this.allCities = res.data.data
    }
  }
})

export default useCityStore

7.在 city.vue 中调用 stores 的数据,先引入,然后解构出数据使用。

import useCityStore from '@/stores/modules/city.js'
import { storeToRefs } from 'pinia'

// 3.从 store 中获取数据
const cityStore = useCityStore()
cityStore.fetchAllCitiesData()
const { allCities } = storeToRefs(cityStore)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值