axios请求

在Jquery的年代,我们普遍用Ajax来请求,但在vue框架里,官方推荐用axios来发送请求。

1.第一步:安装axios

可以通过 npm或yarn来安装。

$ npm install axios
OR
$ yarn add axios

在vue 组件中使用axios

把axios引入到组件页面中

<script>
import axios from "axios";

export default {
 data() {
   return {};
 }
};
</script>

3.一般请求在生命周期mounted里使用

// Test.vue
<script>
import axios from "axios";

export default {
  data() {
    return {};
  },
  mounted() {
    axios.get("https://jsonplaceholder.typicode.com/todos/")
  }
};
</script>

4.用then方法来处理获取的数据

因为页面在请求有答复之前已经渲染,因此我们用promise来保证用请求获取的数据。

mounted() {
  axios.get("https://jsonplaceholder.typicode.com/todos/")
    .then(response => console.log(response))
}

然后就可以在then函数里使用请求回来的数据了。

5.错误处理

用catch方法来处理错误。

mounted() {
axios.get("https://jsonplaceholder.typicode.com/todos/")
  .then(response => console.log(response))
  .catch(err => {
     // Manage the state of the application if the request 
     // has failed      
   })
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值