vue.js - 如何在 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?
解决方案
当 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 数据更改之后添加对此函数的调用。
推荐阅读
- javascript - 在nodejs中销毁对象的事件或回调
- css - 在 Zurb Foundation 5 网格中可以有一个固定宽度的单元格吗?
- scala - 如何从课堂内部使递归akka流“可切换”
- python - tkinter Treeview 将 mysql 数据放入一列
- orm - 解决微服务之间的设计依赖
- angular - 版本 7 的 Angular 应用程序未运行
- linux - 如何在 linux 中强制使具有 's' 权限的命令崩溃?
- jooq - 未加载模式:请检查您的连接设置,以及您的数据库(和您的数据库版本!)是否真的受 jOOQ 支持
- python - 如何在 Python 中使用 OpenCV 将背景的阴影部分计为背景(下图)?
- mysql - MYSQL 搜索返回错误和重复的值