在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
})
}