2017-04-25 29 views
0

我想從rails應用程序中使用json並在頁面上呈現Vue應用程序。但是,似乎我的數據對象從不填充。該應用程序由Vue找到。我想我可以做出成功的任務,並且dom會更新,但是沒有。我嘗試完成後,但沒有。頁面完全呈現後,stuff.things只包含觀察者對象。如何使用vuejs爲數據元素分配ajax響應

下面是腳本:

<script type="text/javascript"> 
    var stuff = new Vue({ 
     el: '#stuff', 
     data: { 
     things: [] 
     }, 
     mounted: function() { 
     // var that; 
     // that = this; 
     $.ajax({ 
      url: '/things.json', 
      success: function(res) { 

      this.things = res; 
      } 
     }).done(function(data){ 
      console.log(data); 
      this.things.push(data); 
     }); 
     } 

    }); 
    </script> 

這裏是div

<div id = "stuff"> 
    <tbody> 
     <tr v-for="thing in things"> 
     <td>hello</td> 
     </tr> 
    </tbody> 
</div> 

這裏是JSON的從頁面的一部分。

[{"id":1,"name":"this thingz","created_at":"2017-04-25T16:54:29.908Z","updated_at":"2017-04-25T17:00:32.519Z"},{"id":2,"name":"dsfsdfd","created_at":"2017-04-25T17:00:56.880Z","updated_at":"2017-04-25T17:00:56.880Z"},{"id":3,"name":"sadsa","created_at":"2017-04-25T17:07:20.084Z","updated_at":"2017-04-25T17:07:20.084Z"},{"id":4,"name":"","created_at":"2017-04-25T17:09:00.686Z","updated_at":"2017-04-25T17:09:00.686Z"},{"id":5,"name":"","created_at":"2017-04-25T17:11:42.989Z","updated_at":"2017-04-25T17:11:42.989Z"}] 

回答

2

當你定義你的ajax回調時,你失去了你的上下文。

$.ajax({ 
    url: '/things.json', 
    success: function(res) { 
    this.things = res; 
    }.bind(this) 
}) 

Example

你也可以用你註釋掉的一些代碼來做到這一點。

mounted: function() { 
    const that = this 
    $.ajax({ 
    url: '/things.json', 
    success: function(res) { 
     that.things = res; 
    } 
    }); 
}