vue-resource achieve get, post, jsonp request
Common data type of request: get, post, jsonp
In addition vue-resource
, you can also use axios
a third party package to fulfill the request for data
vue-resource
Official Documents
vue-resource configuration steps:
- Directly in the page, by
script
the label, the introduction ofvue-resource
the script file;
<script src="./lib/vue-2.4.0.js"></script>
<script src="./lib/vue-resource-1.3.4.js"></script>
- Note: the order is quoted: quote from
Vue
the script file, and then referencedvue-resource
script file;
- Send a get request:
- When initiating get request, by
.then
setting a successful callback function
- When initiating get request, by
getInfo() { // get 方式获取数据
this.$http.get('http://127.0.0.1:8899/api/getlunbo').then(res => {
console.log(res.body);
})
}
- Send a post request:
postInfo() {
var url = 'http://127.0.0.1:8899/api/post';
// post 方法接收三个参数:
// 参数1: 要请求的URL地址
// 参数2: 要发送的数据对象
// 参数3: 指定post提交的编码类型为 application/x-www-form-urlencoded
this.$http.post(url, { name: 'zs' }, { emulateJSON: true }).then(res => {
console.log(res.body);
});
}
- JSONP request the data transmission:
jsonpInfo() { // JSONP形式从服务器获取数据
var url = 'http://127.0.0.1:8899/api/jsonp';
this.$http.jsonp(url).then(res => {
console.log(res.body);
});
}
By global configuration , settings and other parameters BaseURL, for example:
Vue.http.options.root = 'http://vue.studyit.io/'
// 全局启用 emulateJSON 选项
Vue.http.options.emulateJSON = true
Note: If we pass the global configuration, data interface root domain name request, the http request initiated each time alone, url path of the request, it should start with a relative path in front can not take /
, or do not enable the root path splicing .