vue2.X中使用axios

安装axios

命令行打开项目所在位置,执行 yarn add axios

入口文件main.js导入

import {
  getRequest,
  postRequest
} from './libs/api.js'
Vue.prototype.getRequest = getRequest
Vue.prototype.postRequest = postRequest //注入到Vue对象

统一封装公共请求接口(在src根目录下创建libs=》创建test.json)

import axios from 'axios'

//统一请求路径
let base = 'http://localhost:8080'

export const getRequest = (url, params) => {
  return axios({
    method: 'get',
    url: base + url,
    params: params
  })
}

export const postRequest = (url, params) => {
  return axios({
    method: 'post',
    url: base + url,
    data: params,
    transformRequest: [function (data) {
    let ret = ''
    for (let it in data) {
      ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }],
    headers: {
      'content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

引用请求

export default {
  name: 'app',
  components: {
    HelloWorld
  },
  created() {
    this.getRequest('/static/test.json').then(res => {
      console.log(res.data.key)
      //赋值

    })
  }

}

上一篇:IOS UIView 之实例方法篇 Instance Methods


下一篇:基于SpringBoot的SSMP整合案例