记在使用vue-cli中使用axios的心得

我使用的是vue-cli+axios的组合,下面我想记录一下如何在vue-cli中使用axios:

1.使用NPM安装axios并进行配置

首先利用npm进行安装

将终端移至项目目录下,输入

npm install axios

当出现如下图时则表示axios已经下载成功:

安装axios成功

接下来配置axios:

在vue-cli目录中的main.js中:加入以下两行代码:

import axios from 'axios'
Vue.prototype.$axios=axios;

添加到main.js的位置应如图所示:

添加配置

除此之外还可如图中所示添加baseUrl:

this.$axios.defaults.baseURL='地址'

这样就完成了在vue-cli中的配置

使用axios向后端发送请求

我们将一个完整的axios写在某个组件的created()函数中:

let _this=this;
    this.$axios({
      method:'get',
      url:'/MainPage/listAllSorts'
    }).then(function (response) {
      _this.$data.typeInfo=response.data;
    }).catch((function (error) {
      console.log(error.response.data);
    }));

在vue-cli中用此方法使用axios,首先要用this.$axios调用,其中各参数为:

  1. method是发送请求的类型,包括'get'、'post'、‘put’、‘delete’,
  2. url是请求的地址,如果设置了前面的baseURL属性,则可以基于设置的url填写
  3. .then(function(response))用来处理请求后的后端返回,其中response代表返回的请求信息,可以对它任意命名
  4. .catch(function(error))用以处理请求出错的错误返回,其中error代表返回的错误的信息,也可任意命名

以上是一个最简单的请求实例,没有发送数据,如果需要发送参数,则可以使用:

  1. data:{}用以向后端发送json数据
  2. params:{}用以向后端发送合并在url上的数据

下面一个简单的示例:

let _this=this;
    this.$axios({
      method:'get',
      url:'/MainPage/listAllSorts',
      data:{
        key:1231
      }
    }).then(function (response) {
      _this.$data.typeInfo=response.data;
    }).catch((function (error) {
      console.log(error.response.data);
    }));

在这个例子中key是以json的方式传给后端

let _this=this;
    this.$axios({
      method:'get',
      url:'/MainPage/listAllSorts',
      params:{
        key:1231
      }
    }).then(function (response) {
      _this.$data.typeInfo=response.data;
    }).catch((function (error) {
      console.log(error.response.data);
    }));

此例中key被标识在url上,相当于:

http://基地址/MainPage/listAllSorts?key=1231

除此之外还有很多的参数可以添加,在这就不赘述了,各位可以去官网查看