一、通過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格式。