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      
   })
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章