Firebase功能不是实时的

时间:2017-06-23 19:35:33

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

我在VueJS方法中设置了firebase查询

data: {this.todaysEvents}, 
methods : {
    getTodaysEvents (day) {
      this.todaysEvents = []
      const events = db.ref('calendar')
      const query = events.orderByChild('day').equalTo(day)
      console.log(query)

      query.on('value', snap => {
        this.todaysEvents.push(snap.val())
        console.log(this.todaysEvents)
      })
    }

然后通过v-for循环使用它:

<ul class="events-header-list">
    <li :key="index" v-for="(event, index) in todaysEvents[0]" class="chip">{{event}}</li>
</ul>

更新活动时会出现问题。数据不会实时同步。要实现这一目标需要做些什么?

编辑:以下是todaysEvents返回的数据:

[
  {
    "Same Event": {
      "calendar": "Sports",
      "color": "orange",
      "date": "2017-05-22",
      "day": 23,
      "desc": "test description",
      "name": "test"
    },
    "some key": {
      "day": 23,
      "month": 6,
      "name": "cooler event"
    }
  }
]

2 个答案:

答案 0 :(得分:0)

经过一些工作,这归结为更新回调管理Firebase返回值的方式。

new Vue({
    el: '#app',
    data: {
    todaysEvents: [],
  },
  firebase: {
        test: db.ref('calendar')
    },
  methods : {
    getTodaysEvents () {
      const events = db.ref('calendar')
      const query = events.orderByChild('day').equalTo(23)

      query.on('value', snap => {
        let events = snap.val()
        let newEvents = []
        for (let key of Object.keys(events))
          newEvents.push(Object.assign({}, events[key], {key}))
        this.todaysEvents = newEvents
      })
    }
  },
  mounted(){
    setTimeout(() =>
      this.getTodaysEvents(), 500)
  }
})

答案 1 :(得分:0)

value观察者附加到数据列表会将整个数据列表作为单个快照返回,然后您可以循环访问以访问各个子项。见docs

你也可以这样做:

new Vue({
    el: '#app',
    data: {
    todaysEvents: [],
  },
  firebase: {
        test: db.ref('calendar')
    },
  methods : {
    getTodaysEvents () {
      const events = db.ref('calendar')
      const query = events.orderByChild('day').equalTo(23);

      query.on('value', snap =>{
          snap.forEach(childSnap => {
              var childVal = childSnap.val();
              this.todaysEvents.push(childVal);
          });
      });


    }
  },
  mounted(){
    setTimeout(() =>
      this.getTodaysEvents(), 500)
  }
})

以下是fiddle