封装axios请求方法,Vue请求数据

npm 安装 axios

npm install axios -s

axios 发送请求 usage

axios内置了promise模块

	const axios = require('axios');
	axios.get('/user?ID=12345')
  		.then(function (response) {
    		console.log(response);
  		})
  		.catch(function (error) {
    		console.log(error);
  		})
  		.finally(function () {
  			console.log('finally')
 		});

传参方式也可为对象形式

	axios.get('/user', {
    	params: {
      		ID: 12345
    	}
  	})
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .finally(function () {
    console.log('finally')
  }); 

使用async await

async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

封装axios 请求

对axios进行二次封装

export default class Http{

  static async request(method, url, data){
    // 发送请求
    const response = await axios.request({
      method,
      url,
      // baseURL: HOST,
      params: method === 'GET' ? data : null,
      data: method === 'POST' ? data : null
    });
    // 判断是否成功
    return this.isSuccess(response);
  };

  // 判断响应结果是否成功
  static isSuccess(res){
    if(res.status >= 200 && res.status < 300){
      return res;
    }else{
      this.requestExpection(res);
    }
  };

  // 构建失败对象
  static requestExpection(res){
    throw new Error(res);
  };

  // get便捷方法
  static get(url, data){
    return this.request('GET', url, data);
  };

  // post便捷方法
  static post(url, data){
    return this.request('POST', url, data);
  }
}

Vue中请求数据方式

1.在根目录下创建一个Vue.config.js文件,配置正向代理

module.exports = {
  devServer: {
    open: true,
    proxy: {
      '/api': {
        target: 'http://localhost:9000'
      }
    }
  }
}

2.在生命周期函数created中请求数据

homeService.js

import Http from 'Http'
import Api from 'Api'
export const requestGoodsDetailData = async (goodsId)=>{
  const {data: result} = await Http.get(api.GOODS_DETAIL_API, {id: goodsId});
  let banner = [result.data.listPicUrl];
  Object.entries(result.data.itemDetail).forEach(([key, value])=>{
    key.startsWith('picUrl') && banner.push(value);
  })
  // 原价
  let retailPrice = result.data.retailPrice;
  // 现价
  let counterPrice = result.data.counterPrice;
  // 详情
  let detail = result.data.itemDetail.detailHtml;
  // 视频
  let videoInfo = result.data.itemDetail.videoInfo;
  // 选择列表
  let skuSpecList = [...result.data.skuSpecList];
  return {
    retailPrice,
    counterPrice,
    banner,
    detail,
    videoInfo,
  }
}
export default {
  requestGoodsDetailData
} 

Detail.vue

	<template>
		
	</template>
	<script>
		import {requestGoodsDetailData} from 'homeService'
		export default {
			data(){
				return{
					goodsData: {},
					id:0
				}
			},
			methods:{
				aysnc initData(){
					this.goodsData = await requestGoodsDetailData(this.id);
				}
			},
			created(){
				this.initData();
			}
		}
	</script>
	<style>
		
	</style>

在VueX中的action模块中请求数据

address.js

import addressService from 'addressService'
const state = {
  addressList: [],
}
const getters = {
  selectAddress(state){
    if(state.addressList.length > 0){
      return state.addressList[state.selectIndex];
    }else{
      return null;
    }
  }
}
const mutations = {
  setAddressList(state, value){
    state.addressList = value;
  },
  setSelectIndex(state, value){
    state.selectIndex = value;
  }

}
const actions = {
  async getAddressAction(context){
    console.log('请求地址列表');
    let list = await addressService.requestAddressList();
    context.commit('setAddressList', list);
  }
}

export default {
  namespaced: true,
  getters,
  state,
  mutations,
  actions
}

Address.vue

	<template>
		
	</template>
	<script>
		export default {
			methods:{
				getData(){
      				this.$store.dispatch('address/getAddressAction');
    			}
			},
			created(){
				this.getData();
			}
		}
	</script>
	<style>
		
	</style>
发布了2 篇原创文章 · 获赞 9 · 访问量 36

猜你喜欢

转载自blog.csdn.net/qq_37278704/article/details/104417345