【问题标题】:Vue.js: How to map a list of keys to Firebase objects?Vue.js:如何将键列表映射到 Firebase 对象?
【发布时间】:2017-04-29 00:24:45
【问题描述】:

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

现在的问题:我想显示一个列表并显示 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 中的每个条目迭代完整的项目列表。

我的问题:有没有更有效的方法将实际对象映射到对象键列表?对于大量的项目记录,我的方法会很慢。也许我太盲目了,看不到更简单的解决方案?

感谢您的宝贵时间!

【问题讨论】:

  • 从快速扫描vuefire source,我认为它没有内置支持加入此类数据。
  • @FrankvanPuffelen:是的,似乎是这样。还是谢谢!

标签: javascript firebase firebase-realtime-database vue.js vuefire


【解决方案1】:

您的数据是只读的吗?在这种情况下,您可以将过滤器逻辑从您的模板移动到您的数据模块,就像这样(我希望我有意想不到的副作用):

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 数组看起来类似于:items = [{"a": "...", "b": "...", ".key": key}, {"a": "...", "b": "...", ".key": key}, ...]
【解决方案2】:

我认为你必须在那里非规范化/复制一些数据。我也遇到过类似的情况,这段 Firebase 视频为我解决了很多问题:https://youtu.be/ran_Ylug7AE?t=2m22s(链接在 2:22 更新到段落。顺便说一句,整个系列都值得一看。)

我的想法是在“listitems”中添加(Firebase)键,就像您在“items”中所做的那样,那里只有最关键的数据,以便您可以链接到完整的描述

【讨论】:

  • 我正在寻找一种解决方案,我不必复制数据 - 数据库中的重复数据很难维护。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-06
  • 1970-01-01
  • 2017-07-24
  • 1970-01-01
  • 2013-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多