mock数据使用axios发送ajax请求

axios简介

axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:

  • 从浏览器中创建 XMLHttpRequest

  • 从 node.js 发出 http 请求

  • 支持 Promise API

  • 拦截请求和响应

  • 转换请求和响应数据

  • 取消请求

  • 自动转换JSON数据

  • 客户端支持防止 CSRF(跨站请求伪造)

axios使用

  1. 安装axios: npm install axios --save

  2. 在需要使用的文件中引入axios:import axios from 'axios'

  3. json配置路径:config文件夹下的index.js(更改配置文件需重启服务器)

proxyTable: {
    '/api': {
        target: 'http://localhost:8080',
        pathRewrite: {
            '^/api': '/static/mock'
        }
    }
}
  1. 开始使用
data () {
    return {
      lastCity: '',
      swiperList: [],
      iconList: [],
      recommendList: [],
      weekendList: []
    }
  },
  methods: {
    getHomeInfo () {
      axios.get('/api/index.json?city=' + this.city).then(this.getHomeInfoSucc)
    },
    getHomeInfoSucc (res) {
      res = res.data
      if (res.ret && res.data) {
        const data = res.data
        this.swiperList = data.swiperList
        this.iconList = data.iconList
        this.recommendList = data.recommendList
        this.weekendList = data.weekendList
      }
    }
  },
  mounted () {
    this.getHomeInfo()
  }

ps:我用的是Vue2.5开发去哪儿网APP中Home.vue演示的

你可能感兴趣的:(mock数据使用axios发送ajax请求)