Vue.js;在 while 循环中观看的无限循环

Vue.js; Inifinite loop with watch on while loop

我有一个带有数组的 while 循环。然而,这个循环变得无限,因为 dealerCards 数组没有更新,即使它被设置在 watch 中。如何用 watch 属性 更新数组?

<div id="app14">
    <button v-on:click="Stand">Stand</button>
    <p>Dealer: {{dealerCards}}</p>
    <p>Hand: {{dealerHand}}</p>
</div>


<script>
function Draw() {
    return Math.ceil(Math.random() * 13);
}

function CalcHand(cardsArray) {
    cardsArray.forEach(function(c) {
        hand += c;
    });
    return hand;
}


new Vue({
    el: "#app14",
    data: {
        dealerCards: [],
        dealerHand: 0,
    },
    methods: {
        Stand: function() {
            while (this.dealerHand < 17) {
                this.dealerCards.push(Draw());
                console.log("DH: " + this.dealerHand);
            }
        },
    },
    watch: {
        dealerCards: {
            handler: function() {
                this.dealerHand = CalcHand(this.dealerCards);
            },
            deep: true
        },
    }
});

</script>

watch 永远不会运行。通常,同步操作使用 computed,async 使用 watch:

new Vue({
    el: "#app14",
    data: {
        dealerCards: [],
    },
    computed: {
        dealerHand() {
            return CalcHand(this.dealerCards);
        }
    },
    methods: {
        Stand: function() {
            while (this.dealerHand < 17) {
                this.dealerCards.push(Draw());
                console.log("DH: " + this.dealerHand);
            }
        },
    }
});

编辑:我忘了说,通过初始化 hand 来修复 CalcHand 函数。更好的是,将其替换为一行 reducer 并将其移至计算的:

computed: {
    dealerHand() {
        return this.dealerCards.reduce((a, c) => a + c, 0);
    }
},

演示:

function Draw() {
    return Math.ceil(Math.random() * 13);
}

new Vue({
    el: "#app14",
    data: {
        dealerCards: [],
    },
    computed: {
        dealerHand() {
            return this.dealerCards.reduce((a, c) => a + c, 0);
        }
    },
    methods: {
        Stand: function() {
            while (this.dealerHand < 17) {
                this.dealerCards.push(Draw());
                console.log("DH: " + this.dealerHand);
            }
        },
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app14">
    <button v-on:click="Stand">Stand</button>
    <p>Dealer: {{dealerCards}}</p>
    <p>Hand: {{dealerHand}}</p>
</div>