【问题标题】:Vue.Js - data not updatingVue.Js - 数据未更新
【发布时间】:2017-01-11 23:59:20
【问题描述】:

我对 Vue.Js 很陌生,所以请原谅我这个新手问题。我的data() 方法中有一个result 变量,当我尝试在浏览器中使用this.result = result 更新result 变量时,原始变量保持不变。我不';知道我做错了什么。我已经用谷歌搜索了几个小时,但没有找到答案。与往常一样,非常感谢任何帮助。我不知道为什么我的数据没有更新。这是我的代码;

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

【问题讨论】:

  • 检查控制台日志是否有错误。尝试反转 if (response.body === '1') 测试,看看是否是问题所在。
  • 没有控制台错误。我还将if (response.body === '1') 更改为 `if (response.body === '0') 并且它没有做任何事情......
  • 我刚刚完全删除了 if 现在它可以工作了......我想我必须改变条件。谢谢!
  • 太棒了!不要忘记添加答案并标记为已解决。
  • Tom 已经三年了,是时候给这个人解决问题了

标签: vue.js


【解决方案1】:
1 == true //true
1 === true // false

我认为问题可能在于 HTTP 返回true,而不是1

【讨论】:

    【解决方案2】:

    我认为“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;
         }
       });
    }

    【讨论】:

      猜你喜欢
      • 2018-08-08
      • 2022-01-18
      • 1970-01-01
      • 2020-10-15
      • 1970-01-01
      • 2020-11-08
      • 2017-11-11
      • 2017-06-28
      • 2019-10-05
      相关资源
      最近更新 更多