vue中的ajax请求和axios包详解

在vue中,经常会用到数据请求,常用的有:vue-resourse、axios

首先,引入axios

CDN: <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
npm: npm install axios   并在全局的js中引入:import axios from 'axios';

get请求

axios.get('/user?ID=12345')
 .then(function (response) {
  console.log(response);
 })
 .catch(function (error) {
  console.log(error);
 });//欢迎加入全栈开发交流圈一起学习交流:864305860

post请求

//依赖于qs包,将对象转换成以&连接的字符串
//例:
axios.post( postUrl ,qs.stringify({userid:1,username:'yyy'})).then(function (response) {
  consol

配置 axios 使用了 axios 的三个配置项,实际上只有 url 是必须的,完整的 api 可以参考使用说明 为了方便,axios 还为每种方法起了别名,比如上面的 saveForm 方法等价于:

axios.post('/user', context.state.test02)

完整的请求还应当包括 .then 和 .catch

.then(function(res){
 console.log(res)
})//欢迎加入全栈开发交流圈一起学习交流:864305860
.catch(function(err){
 console.log(err)
})

当请求成功时,会执行 .then,否则执行 .catch 这两个回调函数都有各自独立的作用域,如果直接在里面访问 this,无法访问到 Vue 实例 这时只要添加一个 .bind(this) 就能解决这个问题

.then(function(res){
 console.log(this.data)
}.bind(this))

猜你喜欢

转载自my.oschina.net/u/4018697/blog/2960701