javascript - 关于对象遍历的问题

查看:68
本文介绍了javascript - 关于对象遍历的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

<html>
<head>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <title>The Elections</title>
</head>
<!-- listening for keyboard event -->
<body @keyup.c="clear">
<div class="container">
    <h1>People of Vue</h1>
    <ul class="list-group">
        <li v-for="candidate in candidates" class="list-group-item">
            {{candidate.name}} {{candidate.votes}}
            <!-- increase votes 'on:click'-->
            <button class="btn btn-default" @click="vote">Vote</button>
        </li>
    </ul>
    
    <!-- display the name of the 'mayor' using a computed property-->
    <h2>Our mayor is {{mayor.name}}!</h2>


    <pre>{{ $data | json }}</pre>
    <pre>{{ mayor | json }}</pre>
</div>
</body>
<script src="http://v1.vuejs.org/js/vue.js"></script>
<script type="text/javascript">
    var vm = new Vue({
        el: 'body',
        data: {
            candidates: [
                {name: "Mr. Black", votes: 140},
                {name: "Mr. White", votes: 135},
                {name: "Mr. Pink", votes: 145},
                {name: "Mr. Brown", votes: 130},
            ]
        },
        computed: {
            mayor: function () {
                //first we sort the array descending
                var candidatesSorted = this.candidates.sort(function (a, b) {
                    return b.votes - a.votes;
                });
                //the mayor will be the first item
                return candidatesSorted[0];
            }
        },
        methods: {
            //this method runs when the key 'c' is pressed
            clear: function () {
                //Turn votes of all candidate to 0 using map() function.
                this.candidates = this.candidates.map(function (candidate) {
                    candidate.votes = 0;
                    return candidate;
                })
            },
            vote: function(){
                   for(var i=0;i<this.candidates.length;i++){
                       this.candidates[i].votes++; //问题在这里~~~~~~~~~~
                   }
            }
        }
    })
</script>
</html>

当每次点击按钮的时候,所有的votes都++了,怎么样才能单独的votes++呢?

解决方案

<button class="btn btn-default" @click="vote($index)">Vote</button>

vote: function (index) {
    this.candidates[index].votes++;
}

这篇关于javascript - 关于对象遍历的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆