axios, vue-resource進行ajax請求獲取后端數據


一、通過axios完成異步請求:

1.安裝

npm install axios --save

 

2.使用

2.1 方法一:將axios改寫成Vue的原型屬性

1.main.js

import axios from 'axios'
import Vue from 'vue'

Vue.prototype.$ajax = axios;

2.組件中使用:

//get 請求
this.$ajax.get('api/getNewsList') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });

//post 請求
this.$ajax.post('api/getNewsList', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
 

 

3.vuex的store中使用

import Vue from 'Vue'
import Vuex from 'vuex'

import axios from 'axios'

Vue.use(Vuex)
const store = new Vuex.Store({
  // 定義狀態
  state: {
    user: {
      name: 'xiaoming'
    }
  },
  actions: {
    // 封裝一個 ajax 方法
    login (context) {
      axios.post('/api/getNewList', state.user).then((res) => {
         console.log(res.data);
       }.catch((err) => {
         console.log(err);
       })
    }
  }
})

export default store 

2.2 結合vue-axios使用

1.main.js

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'


Vue.use(VueAxios, axios);

2.組件中使用

methods: {
      this.axios.get('api/getNewsList').then((response)=>{
        this.newsList=response.data.data;
      }).catch((response)=>{
        console.log(response);
      })
}

 

二、通過vue-rource完成異步請求(官方已不再維護,建議使用axios)

 其用法跟ajax用法差不多,也就是改變了一些語法格式。從獲取路徑到值的獲取都是一樣的,但是有一點是不同的就是ajax獲取到的數據會自動轉成json格式,而vue-resource獲取到的數據要手動轉成json格式。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM