vue项目中axios请求网络接口封装

本文详细介绍了一种在Vue项目中封装网络请求的方法,包括使用axios和mint-UI进行GET和POST请求的封装,以及如何在项目中全局引入并使用这些封装的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

每个项目网络请求接口封装都是很重要的一块,第一次做Vue项目,我们的封装方法如下:

(1).新建一个js文件,取名api.js

(2).引入 axios ,mint-UI ,如下图:

import axios from 'axios'
import {MessageBox, Toast} from 'mint-ui'

axios.defaults.timeout = 50000//默认请求超时时间
axios.defaults.headers = '请求头'
(3).封装get方法
export function getHttp (url, params = {}) {
  // 创建动画mint-ui
  Indicator.open({
    text: '加载中...',
    spinnerType: 'fading-circle'
  })
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    })
      .then(response => {
        resolve(response.data)
         Indicator.close() // // 关闭动画
      })
      .catch(err => {
        reject(err)
         Indicator.close() // // 关闭动画
        MessageBox.alert('message', err)
      })
  })
}
(4).封装post方法
export function postHttp (url, data = {}) {
  Indicator.open({
    text: '加载中...',
    spinnerType: 'fading-circle'
  })
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(response => {
        if (response.data.status == 1) {
          resolve(response.data)
        } else {
          Toast(response.data.msg)
        }
        Indicator.close() // // 关闭动画
      }, (err) => {
        reject(err)
        Indicator.close()
      })
  })
}

(5).封装后方法的使用

在main.js中引入全局变量

import {getHttp, postHttp} from './config/api'
Vue.prototype.$getHttp = getHttp
Vue.prototype.$postHttp = postHttp

 

    //get网络请求
      this.$getHttp(this.$shopUrl + 'api/product/list',)
        .then((response) => {
          response.result//请求返回数据
       })



    // post网络请求
    
     this.$postHttp(this.$shopUrl + 'api/product/list',)
        .then((response) => {
          response.result//请求返回数据
       })

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值