vue中axios的使用

//第一步
//下载axios的命令 官网:https://www.kancloud.cn/yunye/axios/234845 将axios挂载到vue的原型上,那么在各个组件中都能使用,因为面向对象(继承)
// npm install axios
//第二步
//main.js中引用 import Axios from 'axios'
//将Axios挂载到Vue原型上
Vue.prototype.$https=Axios

//设置公共的url 当用到很多url.且前面的url结构一样时,可以设置公共的url
Axios.default.baseUEL = 'https://www.luffycity.com/api/v1/'

//cours.vue中使用

//
//
// <template>
// <div>
// <div class="categoryList">
// <span @click = 'categoryHandler(index,item.id)' v-for = '(item,index) in categoryList' :key="item.id" :class="{active:index==currentIndex}">{{ item.name }}</span>
// </div>
// <div class="course">
// <ul>
// <li v-for = '(course) in courseList' :key="course.id">
// <h3>{{course.name}}</h3>
// </li>
// </ul>
// </div>
// </div>
// </template>
//
// <script>
// export default {
// name:'Course',
// data(){
// return {
// categoryList:[], //分类列表
// currentIndex:0,
// courseList:[], //课程列表
// categoryId:0, //默认全部课程id
// }
// },
methods:{
//获取 分类列表的数据
getCategoryList(){
          //使用$.https调用axios,因为已经挂在到Vue父类上 ,get请求
this.https.get('course_sub/category/list/') //子路径
.then(res)=>{//成功调用此方法
var data=res.data
if (data.error_no===0){
this.categoryList = data.data;
let obj={
id:0,
name:'全部',
category:0 }
}
this.categoryList.unshift(obj);


}
})
.catch((error)=>{
console.log('获取列表失败',err)

})

#############################官网实例get请求
// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
// 可选地,上面的请求可以这样做
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
 

执行 POST 请求

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

执行多个并发请求

 

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成
  }));
// 发送 GET 请求(默认的方法)
axios('/user/12345');

 




posted @ 2018-12-01 16:00  团子emma  阅读(119)  评论(0)    收藏  举报