Vue 封装网络工具类

1.创建nextwork.js

import axios from 'axios'

// 进行一些全局配置

axios.defaults.baseURL = 'http://127.0.0.1:3000'
axios.defaults.timeout = 3000

// 封装组件的get/post方法

export default {
  get: function (path = '', data = {}) {
    return new Promise(function (resolve, reject) {
      axios.get(path, {
        params: data
      })
        .then(function (response) {
          resolve(response)
        })
        .catch(function (error) {
          reject(error)
        })
    })
  },
  post: function (path = '', data = {}) {
    return new Promise(function (resolve, reject) {
      axios.post(path, data)
        .then(function (response) {
          resolve(response)
        })
        .catch(function (error) {
          reject(error)
        })
    })
  }
}

  2.创建index.js

import NextWork from './nextwork'

export const getBanner = () => NextWork.get('banner')

  3.测试网络工具类

<script>
import { getBanner } from '@/api'

export default {
  name: 'Recommend',
  created () {
    getBanner().then(function (data) {
      console.log(data)
    })
      .catch(function (err) {
        console.log(err)
      })
  }
}
</script>

  

 

posted @ 2020-10-09 16:36  凉城i  阅读(410)  评论(0编辑  收藏  举报