Vue.js数据请求方式
一、 vue-resource
1>通过 yarn 或者 NPM.安装
复制代码
1
2
3$ yarn add vue-resource $ npm install vue-resource
2>在main.js中引用并使用它
复制代码
1
2
3import VueResource from 'vue-resource' Vue.use(VueResource)
3>vue-resource中常用的请求方式(jsonp请求解决跨域问题)
复制代码
1
2
3
4this.$http.get('/someUrl', [config]).then(successCallback, errorCallback); this.$http.post('/someUrl', [body], [config]).then(successCallback, errorCallback); this.$http.jsonp('/someUrl', [config]).then(successCallback, errorCallback);
4>案例
(1)带有参数的post请求
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16{ // POST /someUrl this.$http.post('/someUrl', {foo: 'bar'}).then(response => { // get status response.status; // get status text response.statusText; // get 'Expires' header response.headers.get('Expires'); // get body data this.someData = response.body; }, response => { // error callback }); }
(2)发送带有URL查询参数和自定义头的GET请求。
复制代码
1
2
3
4
5
6this.$http.get('/someUrl', {params: {foo: 'bar'}}).then(response => { // success callback }, response => { // error callback });
更多相关需求请看官网文档:
https://github.com/pagekit/vue-resource/blob/develop/docs/http.md
二、axios
1>使用npm安装
复制代码
1
2$ npm install axios
2>使用案例
(1)带参数的get请求
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17const axios = require('axios'); //一定要引入哦 axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { // always executed });
(2)带参数的post请求
复制代码
1
2
3
4
5
6
7
8
9
10
11
12const axios = require('axios'); axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
以上两种方式还可以通过将相关配置传递给axios来发出请求。例如
复制代码
1
2
3
4
5
6
7
8
9
10// Send a POST request axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } });
更多相关需求请看官网文档:https://github.com/axios/axios
最后
以上就是成就蓝天最近收集整理的关于Vue.js数据请求方式一、 vue-resource二、axios的全部内容,更多相关Vue.js数据请求方式一、内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复