vue-resource是一个通过XMLHttpRequrest或JSONP技术实现异步加载服务端数据的Vue插件。提供了一般的 HTTP请求接口和RESTful架构请求接口,并且提供了全局方法和VUe组件实例方法。在Vue.js 2.0+ 版本推荐使用 axios 来完成 ajax 请求。
参考文献 https://www.runoob.com/vue2/vuejs-ajax.html
Get请求
window.onload = function(){
var vm = new Vue({
el:'#box',
data:{
msg:'Hello World!',
},
methods:{
get:function(){
//发送get请求
this.$http.get('http://www.liulongbin.top:3005/api/getprodlist').then(function(res){
document.write(res.body);
},function(){
console.log('请求失败处理');
});
}
}
});
}
如果需要传递数据,可以使用 this.$http.get(‘get.php’,{params : jsonData}) 格式,第二个参数 jsonData 就是传到后端的数据。
this.$http.get('http://www.liulongbin.top:3005/api/getprodlist',{params : {a:1,b:2}}).then(function(res){
document.write(res.body);
},function(res){
console.log(res.status);
});
post请求
post 发送数据到后端,需要第三个参数 {emulateJSON:true}。
emulateJSON 的作用: 如果Web服务器无法处理编码为 application/json 的请求,你可以启用 emulateJSON 选项。
window.onload = function(){
var vm = new Vue({
el:'#box',
data:{
msg:'Hello World!',
},
methods:{
post:function(){
//发送 post 请求
this.$http.post('http://www.liulongbin.top:3005/api/getprodlist',{name:"谢振瑜",url:"xiezhenyu98.github.io"},{emulateJSON:true}).then(function(res){
document.write(res.body);
},function(res){
console.log(res.status);
});
}
}
});
}
语法 & API
使用全局对象方式 Vue.http 或者在一个 Vue 实例的内部使用 this.$http来发起 HTTP 请求。
// 基于全局Vue对象使用http
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
// 在一个Vue实例内使用$http
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
vue-resource 提供了 7 种请求 API(REST 风格):
get(url, [options])
head(url, [options])
delete(url, [options])
jsonp(url, [options])
post(url, [body], [options])
put(url, [body], [options])
patch(url, [body], [options])
除了 jsonp 以外,另外 6 种的 API 名称是标准的 HTTP 方法。
options 参数说明:
通过如下属性和方法处理一个请求获取到的响应对象:
使用 vue-resource 的 jsonp 处理跨域请求
<div id="app">
请输入关键字:<input type="text" v-model="keyword" @keyup="sendJsonP(keyword)">
<ul>
<li v-for="r in result">{{r}}</li>
</ul>
</div>
<script>
window.onload = function () {
new Vue({
el: '#app',
data: {
keyword: '',
result: ''
},
methods: {
sendJsonP(keyword) {
let url = 'https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web';
this.$http.jsonp(url, {
params: {
wd: keyword
},
jsonp: 'cb'//jsonp默认是callback,百度缩写成了cb,所以需要指定下 }
}).then(res => {
if (res.data.g) {
this.result = res.data.g.map(x => x['q']);
} else {
this.result = [];
}
});
}
}
});
}
</script>
品牌列表案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./lib/vue.js"></script>
<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>
<link rel="stylesheet" href="./lib/bootstrap.min.css">
</head>
<body>
<div id="app">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">添加品牌</h3>
</div>
<div class="panel-body form-inline">
<label>
Name:
<input type="text" v-model="name" class="form-control">
</label>
<input type="button" value="添加" @click="add" class="btn btn-primary">
</div>
</div>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Ctime</th>
<th>Operation</th>
</tr>
</thead>
<tbody>
<tr v-for="item in list" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.ctime }}</td>
<td><a href="#" @click.prevent="del(item.id)">删除</a></td>
</tr>
</tbody>
</table>
</div>
<script>
// 如果我们通过全局配置了,请求数据的接口 根域名,则,每次单独发起 http 请求的时候,请求的url路径,应该以相对路径开头,前面不能带 / ,否则不会启用根路径做拼接。
Vue.http.options.root = 'http://www.liulongbin.top:3005';
// 全局启用 emulateJSON 选项
Vue.http.options.emulateJSON = true;
var vm = new Vue({
el:'#app',
data:{
name:'',
list:[ //存放所有品牌列表的数组
{id:1, name:'五菱宏', ctime:new Date()},
{id:2, name:'众泰', ctime:new Date()}
]
},
created(){ //当 vm 实例的 data 和 method 初始化完毕后,vm实例会自动执行created
this.getAllList();
},
methods:{
add(){//添加品牌列表到后台服务器
// 分析:
// 1、经过查看 数据API接口,发现,要发送一个Post请求,this.$http.post
// 2、this.$http.post() 中接收三个参数
// 2.1、第一个参数:要请求的url地址
// 2.2、第二个参数:要提交给服务器的数据,要以对象形式提交给服务器 { name:this.name }
// 2.3、第三个参数:是一个配置对象,要以哪种表单数据类型提交过去 {emulateJson:true} 以普通表单格式,将数据提交给服务器 application/x-www-form-urlencoded
// 3、在post方法中,使用 .then 来设置成功的回调函数,如果想要成功的结果,需要 result.body
// this.$http.post('api/addproduct', {name:this.name},{emulateJSON:true}).then(result => {
// if(result.body.status === 0){
// //成功了
// alert(result.body.message);
// //添加完成后,只需要手动再调用一下getAllList() 就能刷新品牌列表
// this.getAllList();
// }else{
// alert("添加失败!");
// }
// })
this.$http.post('api/addproduct', {name:this.name}).then(result => {
if(result.body.status === 0){
//成功了
alert(result.body.message);
//添加完成后,只需要手动再调用一下getAllList() 就能刷新品牌列表
this.getAllList();
}else{
alert("添加失败!");
}
})
},
getAllList(){//获取所有品牌列表
// 分析:
// 1、由于已经导入了vue-resource这个包,所以,可以直接通过this.$http 来发起数据请求
// 2、根据接口文档,知道,获取列表的时候,应该发起一个get请求
// 3、this.$http.get('url').then(function(result){})
// 4、当通过 then 指定回调函数之后,在回调函数中,可以拿到数据服务器返回的 result
// 5、先判断 result.status 是否等于0,如果等于0,就成功了,可以把 result.message 赋值给this.list;如果不等于0,可以弹框提示,获取数据失败!
this.$http.get('api/getprodlist').then(result=>{
//注意:通过 $http 获取到的数据,都在 result.body 中放着
var result = result.body;
if(result.status === 0){
// 成功了
this.list = result.message;
}else{
//失败了
alert('获取数据失败');
}
})
// http://www.liulongbin.top:3005/
},
del(id){//删除品牌列表
this.$http.get('api/delproduct/'+id).then(result => {
if(result.body.status === 0){
//删除成功
this.getAllList();
alert("删除成功!");
}else{
alert("删除失败!");
}
})
}
}
})
</script>
</body>
</html>