# 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、使用示例:

  • vuex 中
vuex 模块化的目录结构
├── store
    ├── index.js
    ├── getters.js        # 根级别的 getters
    ├── actions.js        # 根级别的 action
    ├── mutations.js      # 根级别的 mutation
    └── modules
        ├── cart.js
        └── products.js
// @/store/modules/cart.js
import { getCartList } from '@/services/modules/cart'

const state = {
  cartList: []
}

const mutations = {
  changeCartList(state, payload) {
    state.cartList = payload.data
  }
}

// 方式1
const actions = {
  fetchCartListAction({ commit }, PageInfo) {
    const { offset, size } = PageInfo

    return new Promise((resolve) => {
      getCartList(offset, size)
        .then((res) => {
          commit('changeCartList', { data: res.data }) // 修改state(在vuex中需要使用Mutations修改/更新数据)
          resolve('修改state成功了')
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
}

// 方式2
const actions = {
  async fetchCartListAction({ commit }, PageInfo) {
    const { page } = PageInfo

    try {
      const res = await getCartList(page * 20)
      commit('changeCartList') // 修改state(在vuex中需要使用Mutations修改/更新数据)
    } catch (err) {
      console.log(err)
    }
  }
}

export default {
  // 开启命名空间
  namespaced: true,
  state,
  mutations,
  actions
}
  • 组件应用中
<script>
import { mapActions } from 'vuex'

export default {
  methods: {
    ...mapAction('cart', ['fetchCartListAction'])

    // ======================

    // fetchCartListAction() {
    //   this.$store.dispatch('cart/fetchCartListAction')
    // }
  }
}
</script>
更新于 : 8/7/2024, 2:16:31 PM