美文网首页Vue
Vue之vue-resource的一般用法Es5

Vue之vue-resource的一般用法Es5

作者: 衣咸 | 来源:发表于2017-01-06 14:57 被阅读72次

    Vue-resource主要用来做Vue应用与后端数据的交互,我们在使用时有时会要用到Es5的写法,但由于Es5与Es6的语法原因导致写法各异,甚至很多教程都迷惑用错,下面列出几种常见的用法,备查。

    依赖:

    vue-resource
    vue 1.x

    官方的Es6标准写法

    这是官方标准的Es6的简单写法:
    <pre>
    {
    // GET /someUrl
    this.$http.get('/someUrl').then((response) => {
    // success callback
    }, (response) => {
    // error callback
    });
    }
    </pre>

    不用箭头函数的写法:
    <pre>
    //定义json资源的url
    var resource_url = 'http://www.example.com/tweets?q=vuejs&count=10';

    //主要代码区,位于vue实例的methods代码段内
    methods:{
    load: function() {
    this.$http.get(this.resource_url).then(function(response) {
    console.log(response)
    }, function(error){
    console.log(error)
    })
    }
    }
    </pre>

    更深入点参看下面
    <pre>
    {
    // 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');
    
    // set data on vm
    this.$set('someData', response.body);
    

    }, (response) => {
    // error callback
    });
    }
    </pre>

    详细文档参看

    vue-resource Es5的写法

    基本用法如下(此处省略了对于错误处理):

    <pre>
    //定义json资源的url
    var apiUri = "http://www.example.com/tweets?q=vuejs&count=10";
    {
    getPositions: function() {
    //get the url
    this.$http.get(apiUri + 'pages/?pageid=1&limit=10',function (positions) {
    // success callback
    this.$set('positions', positions);
    console.log(this.positions);
    });
    }
    }
    </pre>

    一般容易出错的地方主要在关于错误处理区的位置
    <pre>
    //定义json资源的url
    var apiUri = "http://www.example.com/tweets?q=vuejs&count=10";
    {
    getPositions: function() {
    //get the url
    this.$http.get(apiUri + 'pages/?pageid=1&limit=10',function (positions) {
    // success callback
    this.$set('positions', positions);
    console.log(this.positions);
    }).error(function(data, status, request) {
    // error callback
    console.log('Fail,网址或相关错误!\n错误码:' + status + "\nrequest:" + request);

        });
    }
    

    }
    </pre>

    相关文章

      网友评论

        本文标题:Vue之vue-resource的一般用法Es5

        本文链接:https://www.haomeiwen.com/subject/qbtxbttx.html