首页 > 解决方案 > 这个 Buefy (Vue + Bulma) 函数在这里做什么?

问题描述

我是 Buefy 的新手,对 Vue 也很陌生。Buefy 关于表单的文档在这里有一个示例自动完成,它引用了数据字段上的计算属性。我认为该函数正在输入名称,然后相应地过滤数据数组。

我不确定的是它实际工作的机制,即为什么有两个返回语句,“选项”来自哪里,为什么小写方法在那里......

<template>
    <section>
        <p class="content"><b>Selected:</b> {{ selected }}</p>
        <b-field label="Find a JS framework">
            <b-autocomplete
                rounded
                v-model="name"
                :data="filteredDataArray"
                placeholder="e.g. jQuery"
                icon="magnify"
                clearable
                @select="option => selected = option">
                <template slot="empty">No results found</template>
            </b-autocomplete>
        </b-field>
    </section>
</template>

<script>
    export default {
        data() {
            return {
                data: [
                    'Angular',
                    'Angular 2',
                    'Aurelia',
                    'Backbone',
                    'Ember',
                    'jQuery',
                    'Meteor',
                    'Node.js',
                    'Polymer',
                    'React',
                    'RxJS',
                    'Vue.js'
                ],
                name: '',
                selected: null
            }
        },
        computed: {
            filteredDataArray() {
                return this.data.filter((option) => {
                    return option
                        .toString()
                        .toLowerCase()
                        .indexOf(this.name.toLowerCase()) >= 0
                })
            }
        }
    }
</script>

标签: javascriptvue.jsecmascript-6buefy

解决方案


这是一个 ES6 问题,所以为了理解答案,你需要理解.filter(). 文档

发生的是 JS 中的基本函数式编程。我建议你阅读一下它。

this.data数组也是如此,.filter()它是一种在数组项之间迭代并返回匹配选项的 JS 方法。

所以基本上.filter()返回一个匹配值的数组,然后第二个返回,是返回从过滤器出来的数组到函数(filteredDataArray())被调用的地方。


推荐阅读