vue axios

参考网址地html

https://www.runoob.com/vue2/vuejs-ajax-axios.htmlvue

https://www.jianshu.com/p/7a9fbcbb1114ios

https://www.kancloud.cn/yunye/axios/ajax

axios 发送ajax请求npm

1、下载json

npm install axios --saveaxios

2、配置
在main.js中配置后端

main.jsapi

import axios from 'axios'

Vue.prototype.$axios = axios;

 3、使用app

一、get请求

应用场景:初始化路由,获取数据,通常与生命周期的mounted一块儿使用

格式:

注意:this在then中function的变化

this.$axios.request({
  method: '',
  url: ''
}).then(function (arg) {
  console.log(arg)
}).catch(function (arg) {
  console.log(arg)
})

例子:

export default {
    name: "Course",
    data(){
      return {
        msg: "课程",
        courseList:[
        ]
      }
    },
    methods: {
      initCourse() {
        var that = this;
        // get请求
        this.$axios.get('http://127.0.0.1:8000/api/v1/course/')
          .then(function (response) {
            // console.log(response.data);
            if (response.data.code === 1000){
              that.courseList = response.data.data;
            }
          })
          .catch(function (error) {
            console.log(error);
          });
      }
    },
      mounted() {
        this.initCourse();
      }
}

或使用下面的方式(推荐)

this.$axios.request({
  url:http://127.0.0.1:8000/api/v1/course/',
  method:'GET'
}).then(function (arg) {
  if(arg.data.code === 1000){
    that.detail = arg.data.data
  }else{
    alert(arg.data.error)
  }
}).catch(function (ret) {
    // ajax请求失败以后,获取响应的内容
})

GET请求的url,含有参数

// 直接在 URL 上添加参数 ID=12345
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
 
// 也能够经过 params 设置参数:
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

var that = this
this.$axios.request({
  url:/user,
  method:'GET',
  params:{
    token:1234
  }
}).then(function (arg) {
     console.log(arg)
  }.catch(function (error) {
    console.log(error);
  });
})

三、post请求

应用场景:向后端提交数据(先后的数据交互用json)

格式:

this.$axios.request({
  method: 'POST',
  url: '',
  // 提交的数据
  data: {
    username: this.username,
    password: this.password
  },
  // 自定义请求头的格式
  headers: {
    'Content-Type': 'application/json'
  }
}).then(function (arg) {
  console.log(arg)
}).catch(function (arg) {
  console.log(arg)
})
相关文章
相关标签/搜索