vue的ajax框架有vue-resource和axios;
vue-resource插件非官方库,目前vue1,2都支持;
axios是ajax通用请求库,vue官方推荐;
vue-resource:
主页:https://github.com/pagekit/vue-resource
安装下vue-resource,命令:npm install vue-resource

main.js里全局引入,使用该插件;
import VueResource from 'vue-resource'
声明使用插件 底层会给vm和组件对象添加一个属性 $http
/*
入口js:创建Vue实例
*/
import Vue from 'vue'
import App from './App'
import VueResource from 'vue-resource'
Vue.use(VueResource)
new Vue({
el:'#app',
components:{
App
},
template:'<App/>'
})
App里我们测试一个接口;
let url = 'http://localhost:8080/queryAll';
this.$http.get(url).then(response =>{
// 请求成功
console.log('success')
console.log(response)
},response =>{
// 请求失败,比如404
console.log('error')
console.log(response)
});
编写了一个请求接口用来测试调用:
package com.vue.demo.controller;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class VueController {
//前后的分离的情况下,需要处理跨域
@CrossOrigin(origins = "*",maxAge = 3600)
@RequestMapping(value = "/queryAll")
public String create(){
List<Map> maps = new ArrayList<>();
Map map1 = new HashMap();
map1.put("id",1);
map1.put("name","张三");
Map map2 = new HashMap();
map2.put("id",2);
map2.put("name","王五");
Map map3 = new HashMap();
map3.put("id",3);
map3.put("name","李四");
maps.add(map1);
maps.add(map2);
maps.add(map3);
return "{\"data\":" + JSON.toJSONString(maps) + ",\"code\": 查询成功 }";
}
}
请求成功:

请求失败:http://localhost:8080/queryAll2 ,把路径改下

具体详细用法,请看文档:https://github.com/pagekit/vue-resource/blob/develop/docs/http.md
axios:
主页:https://github.com/axios/axios
安装下axios,命令:npm install axios

axios是哪里用到哪里引入;
import axios from 'axios'
axios调用接口:
let url = 'http://localhost:8080/queryAll';
axios.get(url).then(response => {
//请求成功
console.log('success')
console.log(response)
}).catch(error => {
//请求失败
console.log('error')
console.log(response)
});
请求成功:

请求失败:http://localhost:8080/queryAll2 ,把路径改下

本文介绍了Vue中两种常用的Ajax框架:vue-resource和axios。详细解释了它们的安装配置过程及如何进行GET请求,并展示了请求成功与失败时的处理方式。
666





