单击vue.js从数组中返回随机选择

时间:2018-08-24 19:50:49

标签: vue.js vuejs2 vue-component

我试图在用户单击按钮后从一组条目中获取一个随机项。但是我似乎无法正常工作。我得到的唯一错误是“属性或方法“获胜者”未在实例上定义,但在渲染期间被引用”

我猜测是因为该功能未运行并将值分配给获胜者?有人可以让我知道我要去哪里了吗?

下面的组件代码

<template>
    <div class="container-flex">
        <div class="wrapper">

            <div class="entries">

                <div class="entries__header">

                    <div class="entries__header__title">
                        <p>Competition Entries</p>
                    </div>

                    <div class="entries__header__search">
                        <input 
                            type="text" 
                            name="Search" 
                            class="input input--search" 
                            placeholder="Search..." 
                            v-model="search">
                    </div>
                </div>

                <div class="entries__content">
                    <ul class="entries__content__list">
                        <li v-for="entry in filteredEntries">
                            {{ entry.name }} 
                        </li>

                        <li class="winner">{{ winner }}</li>
                    </ul>
                </div>


                <add-entry :entries.sync="entries"/>

            </div>

            <button 
                @click="pickWinner">Pick Winner</button>

        </div>
    </div>
</template>

<script>

import addEntry from '@/components/add-entry.vue'

export default {
    name: 'entry-list',
    components: {
        addEntry
    },
    data: function() {

        return {
            search: '',
            entries: [
                {
                    name: 'Geoff'
                },
                {
                    name: 'Stu'
                },
                {
                    name: 'Craig'
                },
                {
                    name: 'Mark'
                },
                {
                    name: 'Zoe'
                }
            ],

        }
    },
    methods: {
        pickWinner() {
            winner: this.entries[Math.floor(Math.random() * this.entries.length)]
        }
    },
    computed: {
        filteredEntries() {
            if(this.search === '') return this.entries
            return this.entries.filter(entry => {
                return entry.name.toLowerCase().includes(this.search.toLowerCase())
            })   
        }
    }
}

</script>

1 个答案:

答案 0 :(得分:1)

我将设置一个名为winnerId的属性和一个经过计算的winner并对其进行更新

data: function() {
    return {
        winnerId: null,
        // ...
    }
},
methods: {
    pickWinner() {
        this.winnerId = Math.floor(Math.random() * this.entries.length)
    }
},
computed: {
    winner() {
         return this.entries[this.winnerId] || null;
    }
}

您可能仍需要添加一些额外的错误检查,例如在模板中,如果this.winnerId为null,则不要显示,或者在计算值中,如果winnerId为null,请运行{{ 1}},或您需要的任何其他其他逻辑。