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格式。

 

 

posted @ 2019-03-10 10:20  cecelia  阅读(1216)  评论(0编辑  收藏  举报