vue+axios方法封装(restful,ajax)

2 篇文章 0 订阅

this.$get({

  url: '',

  data: {},

  success: (data) => {}

})


import qs from 'qs'

// axios网络请求
function ajax (Vue, axios) {
  if (ajax.installed) return

  Vue.prototype.$baseURL = axios.defaults.baseURL = (process.env.NODE_ENV === 'production') ? '/api/' : 'http://127.0.0.1:8080/api/'
  // 序列化对象
  Vue.prototype.$serialize = params => qs.stringify(params)
  Vue.prototype.$ajax = function (params, method = 'get') {
    let data = params['data'] || {}
    if (params['loading']) this.isLoading = true
    let [getData, postData, headers] = [null, null, null]
    if (method === 'post') {
      postData = qs.stringify(data)
      headers = {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      }
    } else {
      getData = data
    }
    axios({
      method: method,
      url: params['url'],
      params: getData,
      data: postData,
      headers: headers,
      withCredentials: true
    }).then(res => {
      res = res.data
      if (res.data.authorityCheckState === 1) this.$router.replace('login')
      else if (res.data.authorityCheckState === 2) this.$router.replace('login')
      if (params['loading']) this.isLoading = false
      if (!res.status) {
        if (params['success'] !== undefined) params.success(res.data)
      } else {
        if (!params['fail']) this.$msg(res.message)
        else params.fail(res)
      }
    }).catch(err => {
      if (params['loading']) this.isLoading = false
      if (params['error'] !== undefined) params.error(err)
    })
  }

  // get请求
  Vue.prototype.$get = function (params) {
    this.$ajax(params, 'get')
  }

  // post请求
  Vue.prototype.$post = function (params) {
    this.$ajax(params, 'post')
  }

  // put请求
  Vue.prototype.$put = function (params) {
    params.data['_method'] = 'PUT'
    this.$ajax(params, 'post')
  }

  // patch请求
  Vue.prototype.$patch = function (params) {
    params.data['_method'] = 'PATCH'
    this.$ajax(params, 'post')
  }

  // delete请求
  Vue.prototype.$delete = function (params) {
    this.$ajax(params, 'delete')
  }
}

if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.use(ajax)
}

export default ajax


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值