一、vue-resource
原生异步调用写法太麻烦,而在vue不推荐用jquery,不推荐操作dom。
vue-resource是一个和Vue高度集成的第三方包。他能让我们很方便的去发送数据请求。
二、测试用URL请求资源地址
- 万能地址,基本能响应各种请求。
三、发起异步调用方式
CDN导入。注意:vue-resource需要依赖于Vue,所以Vue的包要先导。
<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>
它向Vue身上挂载了一个属性,后面可以 点.
+方法。
this.$http
this.$http.get(url,[options])
this.$http.post(url,[body],[options])
this.$http.jsonp(url,[options])
- 等等...
后面接.then(successCallback,[errorCallback])
,来拿到和操作服务器返回的数据。(只要遇到.then()
,就说明这个方法是通过Promise封装的)
四、设置请求默认值
请求地址前缀通常是公共的,都写死不利于后期维护。
vue-resource提供了使用全局配置设置默认值。
//设置网页api接口的根域名
Vue.http.options.root = '/root';
Vue.http.headers.common['Authorization'] = 'Basic YXBpOnBhc3N3b3Jk';
在Vue组件选项中设置默认值。
new Vue({
http: {
root: '/root',
headers: {
Authorization: 'Basic YXBpOnBhc3N3b3Jk'
}
}
})
注意:想要root属性(根路径)生效,请求的那个路径必须是相对路径,前面不能带"/"。
vue.http.get(“someurl”),而不是:vue.http.get(“/someurl”)。
五、实例
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>
</head>
<body>
<div id="app">
<input type="button" value="发送get请求" @click="getInfo"/>
<input type="button" value="发送post请求" @click="postInfo"/>
<input type="button" value="发送jsonp请求" @click="jsonpInfo"/>
</div>
<script>
Vue.http.options.root = 'http://jsonplaceholder.typicode.com/';
var vm = new Vue({
el:'#app',
data:{
},
methods:{
getInfo(){ //发起get请求
this.$http.get('users').then(function(res){
console.log(res);
console.log(res.body); //通过.body拿到服务器返回的数据
});
},
postInfo(){ //发起post请求
this.$http.post('users',{}).then(function(res){
console.log(res.body);
});
},
jsonpInfo(){ //发起jsonp请求
this.$http.jsonp('users').then(res=>{
console.log(res.body);
});
}
}
});
</script>
</body>
</html>

如果post请求是提交表单格式的,表单有个提交格式application/x-www-form-urlencode。
手动发起post请求没有表单格式,有些服务器处理不了,需要加opt参数,{emulateJSON:true}
即可。
如果都是每次都需要传入参数很麻烦,可以全局启用。
Vue.http.options.emulateJSON = true;
网友评论