Axios封装和Vuex模块化

2023年1月10日09:29:32

axios封装

我之前是这样写法,如果有params,query参数字段的话字符串拼接。但看网上的有人说不建议放在Vue原型

import axios from 'axios'
Vue.prototype.$ajax= axios // 原型


this.$ajax.get('api/getNewsList')
.then((response)=>{
    this.newsList=response.data.data;
}).catch((response)=>{
    console.log(response);
})

这两天看大佬写Vuex+axios,大佬就是大佬

封装axios

/*
ajax 请求函数模块
*/
import axios from 'axios'
/**
 * 向外部暴漏一个函数 ajax
 * @param {*} url 请求路径,默认为空
 * @param {*} data 请求参数,默认为空对象
 * @param {*} type 请求方法,默认为GET
 */
export default function ajax (url = '', data = {}, type = 'GET') {
  // 返回值 Promise对象 (异步返回的数据是response.data,而不是response)
  return new Promise(function (resolve, reject) {
    // (利用axios)异步执行ajax请求
    let promise // 这个内部的promise用来保存axios的返回值(promise对象)
    if (type === 'GET') {
      // 准备 url query 参数数据
      let dataStr = '' // 数据拼接字符串,将data连接到url
      Object.keys(data).forEach(key => {
        dataStr += key + '=' + data[key] + '&'
      })
      if (dataStr !== '') {
      // 把最后的&去掉,拼成完整的url
        dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
        url = url + '?' + dataStr
      }
      // 发送 get 请求
      promise = axios.get(url)
    } else {
      // 发送 post 请求
      promise = axios.post(url, data)
    }
    promise.then(response => {
      // 成功回调resolve()
      resolve(response.data)
    })
      .catch(error => {
        // 失败回调reject()
        reject(error)
      })
  })
}

使用的话

const BASE_URL = '/api'  // 地址全写,但考虑跨域 / proxy 跨域设置
// params参数 
export const reqAddress = geohash => ajax(`${BASE_URL}/position/${geohash}`)
// query参数
export const reqSearchShop = (geohash, keyword) => ajax(BASE_URL + '/search_shops', {geohash, keyword})

Vuex模块化

Axios封装和Vuex模块化
index.js

/*
vuex最核心的管理对象store
组装模块并导出 store 的地方
 */
// 首先引入Vue及Vuex
import Vue from 'vue'
import Vuex from 'vuex'

// 引入四个基本模块
import state from './state'
import mutations from './mutations'
import actions from './actions'
import getters from './getters'

// 一定要声明使用插件
Vue.use(Vuex)

// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})

挂载Vue实例
使用的话this.$

import store from './store'

new Vue({
  el: '#app',
  components: { App },
  template: '<App/>',
  // 为根组件加入路由
  router,
  store
})

state.js

export default {
  categorys: [], // 食品分类数组
  goods: [], // 商品列表
  info: {}, // 商家信息
}

mutation-types.js

export const RECEIVE_CATEGORYS = 'receive_categorys' // 接收分类数组
export const RECEIVE_GOODS = 'receive_goods' // 接收商品数组
export const RECEIVE_INFO = 'receive_info' // 接收商家信息

mutations.js

/*
vuex 的 mutations 模块
*/
import Vue from 'vue'
import {
  RECEIVE_CATEGORYS,
  RECEIVE_INFO,
  RECEIVE_GOODS} from './mutation-types'
// [方法名](state,{param}){}
export default {
  [RECEIVE_CATEGORYS] (state, {categorys}) {
    state.categorys = categorys
  },
  [RECEIVE_INFO] (state, {info}) {
    state.info = info
  },
  [RECEIVE_GOODS] (state, {goods}) {
    state.goods = goods
  }
}

actions.js

/*
Action:通过操作mutation间接更新state的多个方法的对象
 */

// 注意要引入api接口函数
import {
  reqCategorys,
  reqShopGoods,
  reqShopInfo,
} from '../api'
import {
  RECEIVE_CATEGORYS,
  RECEIVE_GOODS,
  RECEIVE_INFO} from './mutation-types'
export default {
  // 异步获取食品分类列表
  async getCategorys ({commit}) {
    // 发送异步ajax请求
    const result = await reqCategorys()
    // 提交一个mutation
    if (result.code === 0) {
      const categorys = result.data
      commit(RECEIVE_CATEGORYS, {categorys})
    }
  },

  // 异步获取商家列表
  async getShops ({commit, state}) {
    // 对象的结构赋值
    const {longitude, latitude} = state
    // 发送异步ajax请求
    const result = await reqShops(longitude, latitude)
    // 提交一个mutation
    if (result.code === 0) {
      const shops = result.data
      commit(RECEIVE_SHOPS, {shops})
    }
  },
  // 异步获取商家信息
  async getShopInfo ({commit}) {
    const result = await reqShopInfo()
    if (result.code === 0) {
      const info = result.data
      commit(RECEIVE_INFO, {info})
    }
  },
}

getters.js

/*
包含多个基于state的getter计算属性的对象
 */
export default {
  totalPrice (state) {
    return state.cartFoods.reduce((preTotal, food) => preTotal + food.count * food.price, 0)
  },
}

将数据放在Vuex中,在页面中调用。详情还是看官方文档。

// state
computed: {
    ...mapState(['info', 'categorys', 'goods']),
    }
// mutations 同步
// action 异步 提交mutations
    // 通过this.$store.dispatch 方法触发调用Action
    this.$store.dispatch('getAddress')
	// this.getAddress()
   
    this.getUserInfo()
  },
  methods: {
    ...mapActions(['getUserInfo'])
  }

  • 作者:Posden
  • 原文链接:https://blog.csdn.net/weixin_44420276/article/details/88852131
    更新时间:2023年1月10日09:29:32 ,共 3482 字。