首页 > 解决方案 > 如何在 Firestore db 更改上重新加载 dom 元素?

问题描述

我们正在使用 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.jsgoogle-cloud-firestorevuefire

解决方案


当 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 数据更改之后添加对此函数的调用。


推荐阅读