欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue项目中axios请求网络接口封装的示例代码

程序员文章站 2023-03-30 17:25:46
每个项目网络请求接口封装都是很重要的一块,第一次做vue项目,我们的封装方法如下: (1).新建一个js文件,取名api.js (2).引入 axios ,mint-u...

每个项目网络请求接口封装都是很重要的一块,第一次做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 = '请求头'

(2).封装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//请求返回数据
  })

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。