【问题标题】:How to reload dom elements on Firestore db change?如何在 Firestore db 更改上重新加载 dom 元素?
【发布时间】:2018-09-06 19:07:58
【问题描述】:

我们正在使用 vue.js、vuefire 和 Firestore 构建一个应用,其中一个用户有多个餐厅。在我们的 Dashboard 中,则需要能够在餐厅之间“切换”以进行更改(例如,更新菜单)。问题是在“菜单”布局上,当我切换餐厅时,菜单不会改变。

我们有一个 Switcher 组件,可以在 db 和 vuex 商店中更改用户的“activeRestaurant”。

这里是来自 store.js 的相关代码:

switchRestaurant({ commit }, payload) {
  console.log(payload)
  db.collection('users').doc(payload.id).update({
    activeRestaurant: payload.activeRestaurant,
  })
  const activeRest = {
    activeRestaurant: payload.activeRestaurant,
    id: payload.id,
  }
  commit('setUser', activeRest)
}

在我们的菜单布局中,菜单项呈现为:

<li v-for="(regularItem, idx) in regularItems" :key="idx">
    <h4>{{ regularItem.item.name }}</h4>
</li>

computed: {
  userAccount () {
    return this.$store.getters.user
  }
},
firestore () {
  return {
    user: db.collection('users').doc(this.userAccount.id),
    regularItems: db.collection('items').where("restaurant", "==", 
    this.userAccount.activeRestaurant.id)
  }
},

如果我从餐厅 A 切换到餐厅 B,什么都不会改变。但是,如果我随后导航到另一个布局,它会呈现餐厅 B 的内容。如果我然后单击返回我的菜单,它会显示餐厅 B 的菜单项。

当我切换餐厅时,如何使菜单内容从餐厅 A 更改为 B?

【问题讨论】:

    标签: vue.js google-cloud-firestore vuefire


    【解决方案1】:

    当 activeRestaurantId 更改时,VueFire 似乎没有再次调用数据库。您可以在一个方法中重写此代码,以便在该变量更改时进行更新,如下所示:

    data () {
      return {
        'regularItems': []
      }
    }
    methods: {
      updateActiveRestaurant () {
        db.collection('items').where("restaurant", "==", this.userAccount.activeRestaurant.id)
        .get()
        .then(function (querySnapshot) {
          querySnapshot.forEach(function (doc) {
            var item = doc.data()
            item.id = doc.id
            this.regularItems.push(item)
          }.bind(this))
        }.bind(this))
      }
    }
    

    然后您可以在创建时以及在 activeRestaurant 数据更改之后添加对此函数的调用。

    【讨论】:

    • 感谢 Dylan... 仍在为此苦苦挣扎。如果我的切换器和我的 menuItems 是不同的组件,我将如何管理它?
    猜你喜欢
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 2014-10-11
    • 2017-11-12
    • 2023-03-02
    • 2015-02-23
    • 2012-05-18
    • 2021-07-24
    相关资源
    最近更新 更多