【问题标题】:how can i return data from this.$http.get in vue js我如何在 vue js 中从 this.$http.get 返回数据
【发布时间】:2015-11-12 03:09:05
【问题描述】:

您好,我在 laravel 5 中使用 vue js 在我的 ajax 调用中返回数据时遇到问题。我有一个状态数组并在循环内调用 ajax 函数。现在的问题是 ajax 似乎无法返回值。这是我的代码:

ready: function() {

    var dData = {};

    for (var i=0; i<this.pState.selectedState.length; i++){
        dData = this.displayCounty(this.pState.selectedState[i])
    }
    console.log(dData);

},
methods:{

    displayCounty: function(val){
        var nData = {};

        // ajax get County list
        this.$http.get('/api/counties/' + val )
            .success(function(counties){
               return counties;
            })
            .error(function(){

            }) //ajaxcall

    }// displaCounty
}

有什么想法吗?

【问题讨论】:

    标签: ajax laravel-5 vue.js


    【解决方案1】:

    如果您只想将返回的结果分配给变量,请尝试以下操作:

    ready: function() {
        this.getCounties;
    },
    
    data: {
        counties: []
    },
    
    methods:{
    
        getCounties: function(val){
    
            // ajax get County list
            this.$http.get('/api/counties/' + val )
                .success(function(counties){
                   this.counties = counties;
                })
                .error(function(){
    
                }); //ajaxcall
    
        } // displayCounty
    }
    

    【讨论】:

    • 我所做的是将其分配给一个新变量,例如“var self = this”,然后在 ajax 中我只需将国家分配给 self.countries,我现在就可以获取值了。
    • 如果我不想将该结果分配给国家数据,该怎么办?
    【解决方案2】:

    我认为您误解了$http.get 的异步性质。 return counties 的返回值不会影响 displayCounty 的返回值。 displayCounty 立即返回 null,而 return counties 稍后什么也不做。

    在这种情况下使用的一个好策略是在 View Model 上设置 success 回调设置 counties。然后您可以在counties 上设置一个观察者,并在数据发生变化时对其进行处理。

    【讨论】:

      【解决方案3】:

      Ready 已被 Vue.js 2 中的 Mounted 取代

      你应该使用这个:

      ready: mounted() {
          this.getCounties;
      },
      

      【讨论】:

        猜你喜欢
        • 2017-06-23
        • 2017-10-13
        • 2019-11-22
        • 2015-06-29
        • 1970-01-01
        • 2018-08-05
        • 1970-01-01
        • 1970-01-01
        • 2017-12-16
        相关资源
        最近更新 更多