# 1、结构:

├── services
    ├── index.js
    ├── request # axios封装
    │   ├── index.js
    │   └── config.js
    └── modules # api管理
        ├── cart.js
        └── products.js
// @/services/index.js

import RenRequest from './request/index.js'
import { BASE_URL, TIMEOUT } from './request/config.js'

export const shopRequest = new RenRequest({
  baseURL: BASE_URL,
  timeout: TIMEOUT
})

export * from './modules/cart.js'

# 2、axios 封装:

// @/services/request/config.js

export const BASE_URL = 'http://xxxxx.com'
export const TIMEOUT = 10000
// @/services/request/index.js

import axios from 'axios'

class RenRequest {
  constructor(config) {
    this.instance = axios.create(config)

    // 响应拦截
    this.instance.interceptors.response.use(
      (response) => {
        return response.data
      },
      (error) => {
        return error
      }
    )
  }

  request(config) {
    return this.instance.request(config)
  }

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

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

export default RenRequest

# 3、api 管理:

// @/services/modules/cart.js

import { shopRequest } from '../index.js'

export function getCartList(offset = 0, size = 20) {
  return shopRequest.get({
    url: 'carts/list',
    params: {
      offset,
      size
    }
  })
}

# 4、使用示例:

  • Pinia 中
Pinia 模块化的目录结构

  Pinia 中的每一个文件就是一个单独的 store,所以不存在什么模块划分的说法。

├── stores
    ├── index.js
    ├── cart.js
    └── products.js
// @/store/cart.js
import { getCartList } from '@/services/modules/cart'

export const useCounter = defineStore('main', {
  state() {
    return {
      cartList: []
    }
  },
  actions: {
    // 方式1
    fetchCartListAction(payload) {
      const { offset, size } = payload

      return new Promise((resolve) => {
        getCartList(offset, size)
          .then((res) => {
            this.cartList = res.data // 可以直接修改state啦😘(再也不要像vuex那样commit、像redux那样和普通action区分了)
            resolve('修改state成功了')
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 方式2
    async fetchCartListAction(payload) {
      const { offset, size } = payload

      try {
        const res = await getCartList(offset, size)
        this.cartList = res.data // 可以直接修改state啦😘(再也不要像vuex那样commit、像redux那样和普通action区分了)
      } catch (err) {
        console.log(err)
      }
    }
  }
})
  • 组件应用中
<script setup>
  import { useCart } from '@/stores/cart'

  const cartStore = useCart()

  // 使用
  // cartStore.fetchCartListAction()
</script>
更新于 : 8/7/2024, 2:16:31 PM