Vue.js:如何将键列表映射到Firebase对象?

5

我基于Vue.js开发了一个小型Web应用程序,使用Firebase来存储和同步数据。我存储 items(例如具有属性titlesubtitle的)和带有属性listitemslists,其中存储了由Firebase生成的items的键数组。结构如下:

enter image description here

现在的问题是:我想显示一个列表并展示listitems属性中的项,我是这样做的:

组件:

var ShowList = Vue.extend({
    template: '#show-list',
    firebase: {
        // get all existing items from firebase
        items: firebase.database().ref('items')
    },
    data: function () {
        // get list item keys of list 'list_id' and bind it to this.list
        this.$bindAsObject('list', listsRef.child(this.$route.params.list_id));
        return {
            list: this.list
        };
    }
});

模板:

<!-- show a list -->
<template id="show-list">
    <ul v-if="list.items != ''">
        <li v-for="key in list.items">        <!-- I would like to not being forced to -->
            <template v-for="item in items">  <!-- iterate the whole list of existing items -->
                <span v-if="item['.key'] == key">
                    {{ item.title }}
                </span>
            </template>
        </li>
    </ul>
    <div v-else>No items.</div>
</template>

如您所见,我必须对每个list.items中的条目迭代整个项目列表两次。

我的问题是:是否有更有效的方法将实际对象映射到对象键列表?对于大量项目记录,我的方法会非常慢。也许我只是太糊涂,看不到更简单的解决方案?

感谢您的时间!


1
从快速扫描vuefire源代码来看,我认为它没有内置支持连接此类数据。 - Frank van Puffelen
@FrankvanPuffelen:是的,看起来是这样。无论如何,谢谢! - andreas
2个回答

0

我认为你需要对一些数据进行去规范化/复制。我曾经遇到过类似的情况,这个Firebase视频为我解决了很多问题:https://youtu.be/ran_Ylug7AE?t=2m22s(链接已更新至2:22处。整个系列都值得观看)。

我的建议是在“listitems”中添加(Firebase)键,就像你在“items”中所做的那样,只包含最关键的数据,以便你可以链接到完整的描述。


我正在寻找一种解决方案,不需要复制数据 - 数据库中的重复数据很难维护。 - andreas

0

你的数据是只读的吗?如果是这样,你可以将过滤逻辑从模板移动到数据模块中,像这样(我预计会有意外的副作用):

data: function () {
    // get list item keys of list 'list_id' and bind it to this.list
    this.$bindAsObject('list', listsRef.child(this.$route.params.list_id));
    var items = firebase.database().ref('items')
    var activeItems = this.list.items.map(function(key) {
        return items[key]
    })
    return {
        activeItems: activeItems;
    };
}

好主意。问题在于,您不能使用items[key],因为items是一个简单的项目对象列表。项目对象具有键作为单独属性。项目数组类似于:items = [{"a": "...", "b": "...", ".key": key}, {"a": "...", "b": "...", ".key": key}, ...] - andreas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接