vue-resource

除了vue-resource外,也可使用axios的第三方包实现数据请求

发送get/post/jsonp请求

示例代码:

 1    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
 2     <script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.1"></script>
 3     <script>
 4         var vm = new Vue({
 5             el: '#app',
 6             data: {},
 7             methods: {
 8                 getInfo() {
 9                     //发起get请求,通过.then设置成功的回调函数
10                     this.$http.get('https://jsonplaceholder.typicode.com/todos/1').then(result => {
11                         //通过result.body拿到服务器返回的成功数据
12                         console.log(result.body)
13                     })
14                 },
15                 postInfo() {
16                     //手动发起的post请求默认没有表单格式,需要设置
17                     this.$http.post('http://jsonplaceholder.typicode.com/posts', {}, { emulateJSON: true }).then(result => {
18                         console.log(result.body)
19                     })
20                 },
21                 jsonpInfo() {
22                     this.$http.jsonp('https://jsonplaceholder.typicode.com/todos/1').then(result => {
23                         console.log(result.body)
24                     })
25                 }
26             }
27         })
28     </script>

 全局配置数据接口的根域名

 (1)使用全局配置设置默认值

如果使用了根域名配置,请求的数据接口中不url路径应以相对路径开头,前面不能带`/`,否则不会启用根路径拼接。

Vue.http.options.root = 'https://jsonplaceholder.typicode.com';
var vm = new Vue({
    el: '#app',
    data: {},
    methods: {
        getInfo() {
            this.$http.get('todos/1').then(result => {
                console.log(result.body)
            })
        }
    }
})

(2)在Vue组件选项中设置默认值

var vm = new Vue({
    el: '#app',
    data: {},
    http: {
        root: 'https://jsonplaceholder.typicode.com'
    },
    methods: {
        getInfo() {
            this.$http.get('todos/1').then(result => {
                console.log(result.body)
            })
        }
    }
})

 全局配置emulateJSON

设置全局的表单格式为application/x-www-form-urlencoded格式

Vue.http.options.emulateJSON = true;
var vm = new Vue({
    el: '#app',
    data: {},
    http: {
        root: 'https://jsonplaceholder.typicode.com'
    },
    methods: {
        postInfo() {
            this.$http.post('posts', {}).then(result => {
                console.log(result.body)
            })
        }
    }
})

 

转载于:https://www.cnblogs.com/lianglanlan/p/10229790.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值