1. 程式人生 > 其它 >Vue專案中使用axios傳送ajax請求

Vue專案中使用axios傳送ajax請求

技術標籤:ajaxjsvuejavascriptpost

首先安裝axios

npm install axios -S

在main.js中引入

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

傳送Get請求

this.$axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 上面的請求也可以這樣做
this.$axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

傳送Post請求

this.$axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });