前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >vue项目中axios请求网络接口封装

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

作者头像
honey缘木鱼
发布2018-12-27 15:41:10
2.2K0
发布2018-12-27 15:41:10
举报
文章被收录于专栏:娱乐心理测试娱乐心理测试

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

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

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

代码语言:javascript
复制
import axios from 'axios'
import {MessageBox, Toast} from 'mint-ui'

axios.defaults.timeout = 50000//默认请求超时时间
axios.defaults.headers = '请求头'

(2).封装get方法

代码语言:javascript
复制
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方法

代码语言:javascript
复制
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中引入全局变量

代码语言:javascript
复制
import {getHttp, postHttp} from './config/api'
Vue.prototype.$getHttp = getHttp
Vue.prototype.$postHttp = postHttp
代码语言:javascript
复制
    //get网络请求
      this.$getHttp(this.$shopUrl + 'api/product/list',)
        .then((response) => {
          response.result//请求返回数据
       })

    // post网络请求

     this.$postHttp(this.$shopUrl + 'api/product/list',)
        .then((response) => {
          response.result//请求返回数据
       })
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.12.17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档