Vue js,无法传递数据

时间:2015-12-24 23:04:36

标签: vue.js

我有简单的存款计算。这是代码。

app.js:

    el: '#calcbox',

data: {

    newCalc: {
        summ: '50000',
        currency: 'USD',
        duration: '',
        percents: '',

    },

    calcResult: '',

},

computed: {

    percents() {

        var id = $("#deposit_id").val();
        var url = "/get_percent/"+ id + '/' + this.newCalc.currency + '/' + this.newCalc.duration;

        this.$http.get(url, function(response){
        return this.newCalc.percents = response;
        });

    },

    calcResult() {

        var deposit_id = $("#deposit_id").val();
        var url = "/api/calc/"+ deposit_id + '/' + this.newCalc.summ + '/' + this.newCalc.currency + '/' + this.newCalc.duration;

        this.$http.get(url, function(response){
        return this.calcResult = response;

        });

    }

},

前端:

<span>@{{newCalc.percents}}%:</span>

<span>@{{calcResult}}:</span>

所以问题是结果没有出现在前端,console.log显示正确的结果。

百分比值显示良好。

1 个答案:

答案 0 :(得分:0)

calcResult() {

    var deposit_id = $("#deposit_id").val();
    var url = "/api/calc/"+ deposit_id + '/' + this.newCalc.summ + '/' + this.newCalc.currency + '/' + this.newCalc.duration;

    this.$http.get(url, function(response){
         return this.calcResult = response;
    });

}

添加.bind(this)

 calcResult() {

    var deposit_id = $("#deposit_id").val();
    var url = "/api/calc/"+ deposit_id + '/' + this.newCalc.summ + '/' + this.newCalc.currency + '/' + this.newCalc.duration;

    this.$http.get(url, function(response){
        return this.calcResult = response;

    }.bind(this));

}

或者使用胖箭头表示法,因为您使用的是ES6语法

 calcResult() {

    var deposit_id = $("#deposit_id").val();
    var url = "/api/calc/"+ deposit_id + '/' + this.newCalc.summ + '/' + this.newCalc.currency + '/' + this.newCalc.duration;

    this.$http.get(url, response => {
    return this.calcResult = response;

    });

}

this回调中的.then与您的vue方法之外或之内的内容不同