zoukankan      html  css  js  c++  java
  • vue-resource的使用

    • 安装
    npm i vue-resource --save-dev
    
    • 引入
    import Vueresource from 'vue-resource'
    
    • 注册
    Vue.use(Vueresource)
    
    • 使用
    // 便捷方法
    this.$http.get({url:'api/index', headers:{Authorization:'Basic Yxsdlfjui'}})
    .them((data) => {
        // 请求成功
    }, (error) => {
        // 请求失败
    })
    
    // 底层方法
    Vue.http({
        url:'api/index2',
        method: 'POST',
        data: {
            param: 1
        }
    })
    .then((data) => {
        // 请求成功
    }, (error) => {
        // 请求失败
    })
    
    • 便捷方法

    便捷方法是对底层方法的封装

    this.$http.get(url,{data},{opation})

    • 参数

      • url: 字符串, 请求地址
      • data: 对象或者字符串
      • opation: 对象, 传入的对象来控制请求
    • 返回的response对象

      • data(对象或者字符串): 服务器返回的数据, 已用JSON.parse解析
      • ok(布尔值): 当HTTP响应码在200-299区间是true, 表示响应成功
      • status(数值): HTTP响应码
      • statusText(字符串): HTTP响应状态文本描述
      • headers(函数): 响应头信息
    • 返回Promise对象
      执行HTTP调用后会返回一个Promise对象, 该对象提供了then, catch, finally注册回调函数

    var promise = this.$http.post('api/index');
    promise.this(function(response){
        // 成功回调
    }, function(error){
        // 失败回调
    })
    
    promise.catch(function(error){
        // 失败回调
    })
    promise.finally(function(){
        // 失败或者成功后都会执行此函数
    })
    // 所有回调函数的`this`都指向组件实例
    
    • JSONP请求

      • 设置methos的值为JSONP即可
      • this.$http.jsonp()也可以
    • 修改发给服务器端的数据类型

    默认情况下, 发送给服务器请求头的Content-Typeapplication/json

    有时我们需要将数据提交为指定的类型

    1 . 全局headers配置

    Vue.http.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
    

    2 . 实例配置

    this.$http.post(
        'api/index',
        // 成功回调
        function(data, status, request) {
            if(status === 200) {
                // 成功
            }
        },
        // 实例配置
        {
            headers: {
                'Content-Type':'multipart/form-data'
            }
        }
    )
    

    实力配置优先于全局配置

  • 相关阅读:
    [NOIP2011]选择客栈
    [学习笔记]字符串的一些基本操作
    [学习笔记]树链剖分
    [宁波集训]0827Day1
    [POI2015]LOG(树状数组)
    [学习笔记]树形dp
    货车运输(最大生成树+倍增LCA)
    POJ 3617 Best Cow Line 贪心算法
    C++ STL next_permutation() prev_permutation(a,a+n)用法。
    POJ 2386 Lake Counting dfs
  • 原文地址:https://www.cnblogs.com/mr-yuan/p/7875785.html
Copyright © 2011-2022 走看看