2017-01-11 67 views
1

我對Vue.Js很新,所以請原諒我這個新手問題。我在data()方法中有一個result變量,當我嘗試使用this.result = result更新result變量時,在瀏覽器中,原始變量保持不變。我不';知道我做錯了什麼。我搜索了幾個小時,但沒有找到答案。一如既往,非常感謝任何幫助。我不知道爲什麼我的數據沒有更新。這是我的代碼;Vue.Js - 數據沒有更新

play.js

Vue.component('game', { 
     template: '#game-template', 

     data: function() { 
      return { 
       ready: null, 
       result: 0 
      } 
     }, 
     props: ['gameid'], 


     methods: { 
      loadGame: function() { 
       this.$http.get('../api/games/ready/' + this.gameid).then(function (response) { 
        if (response.body === '1') { 
         // process coinflip upon ready game 
         var result = Math.floor((Math.random() * 2) + 1); 
         this.result = result; 
         console.log(this.result); 


        } 

       }.bind(this)); 
      } 
     }, 

     ready: function() { 
      this.loadGame(); 

      setInterval(function() { 
       this.loadGame(); 
      }.bind(this), 5000); 
     } 
    }); 

new Vue({ 
    el: '#app' 
}); 

查看:

extends('layouts.app') 

@section('content') 

    <div id="app"> 
     <game v-bind:gameid="{{$gameid}}"></game> 
    </div> 

    <template id="game-template"> 
     <div> 
      <strong>Result:</strong> @{{ result }} 

     </div> 
    </template> 

    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.js"></script> 

    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.0.3/vue-resource.js"></script> 

    <script src="../js/play.js"></script> 

    @endsection 
+0

檢查控制檯日誌中的錯誤。嘗試顛倒'if(response.body ==='1')'測試來看看是否有問題。 – djones

+0

沒有控制檯錯誤。我也將'if(response.body ==='1')'改爲'if(response.body ==='0')並且它沒有做任何事情...... –

+0

我剛剛刪除了if完全現在它作品...我想我必須改變條件。謝謝! –

回答

0
1 == true //true 
1 === true // false 

我想問題可能在於,HTTP返回true,不1的事實。

0

我認爲'this'關鍵字的值與您的預期不同。試試這個辦法:

loadGame: function() { 
 
    let self = this; 
 
    this.$http.get('../api/games/ready/' + self.gameid).then(function (response) { 
 
    if (response.body === '1') { 
 
     var result = Math.floor((Math.random() * 2) + 1); 
 
     self.result = result; 
 
    } 
 
    }); 
 
}