javascript - Vue,火库 : how to display LIVE data after merging collections

标签 javascript firebase vue.js google-cloud-firestore vuex

见下方编辑

我比 my last question 有了很大的改进,但经过几天的工作,我再次陷入困境。
将 Vue、Vue-router、Vuex 和 Vuetify 与 Google 上的数据一起使用可以 Firestore
我想实时更新我的​​数据,但我找不到这样做的方法。
我是否需要重组,例如将产品和类别转移到一个集合中?
或者是否有任何绑定(bind)或查询魔法来完成这项工作。
正如您在下面看到的,它可以很好地加载点击数据,但我需要实时绑定(bind) 因为你可以打开页面,有人可以卖掉最后一 block (amountLeft = 0)。 (还有很多 future 的想法)。
我的数据结构如下:

categories: {
  cat_food: {
    name: 'Food'
    parentCat: 'nC'
  },
  cat_drinks: {
    name: 'Food'
    parentCat: 'nC'
  },
  cat_beer: {
    name: 'Beer'
    parentCat: 'cat_drinks'
  },
  cat_spritz: {
    name: 'Spritzer'
    parentCat: 'cat_drinks'
  },
}

products: {
  prod_mara: {
    name: 'Maracuja Spritzer'
    price: 1.5
    amountLeft: 9
    cat: ['cat_spritz']
  },
  prod_capp: {
    name: 'Cappuccino'
    price: 2
    cat: ['cat_drinks']
  },
}
类别和产品构成一棵树。 GIF 显示我打开类别以显示产品。当您有价格标签时,您会看到它是一种产品。
您可以看到有两个类别具有相同的父项 (cat_drinks)。
产品 prod_capp 也分配给类别并与类别并排显示。
Opening categories
我目前以这种方式获取数据:
catOrProd.js
import { catsColl, productsColl } from '../firebase'

const state = {
  catOrProducts: [],
}

const mutations = {
  setCats(state, val) {
    state.catOrProducts = val
  }
}

const actions = {
  // https://vuefire.vuejs.org/api/vuexfire.html#firestoreaction

  async bindCatsWithProducts({ commit, dispatch }, CatID) {
    if (CatID) {
      // console.log('if CatID: ', CatID)
      await Promise.all([
        catsColl.where('parentCat', '==', CatID).orderBy('name', 'asc').get(),
        productsColl.where('cats', 'array-contains', CatID).orderBy('name', 'asc').get()
      ])
        .then(snap => dispatch('moveCatToArray', snap))
    } else {
      // console.log('else CatID: ', CatID)
      await Promise.all([
        catsColl.where('parentCat', '==', 'nC').orderBy('name', 'asc').get(),
        productsColl.where('cats', 'array-contains', 'nC').orderBy('name', 'asc').get()
      ])
        .then(snap => dispatch('moveCatToArray', snap))
    }
  },

  async moveCatToArray({ commit }, snap) {
    const catsArray = []
    // console.log(snap)
    await Promise.all([
      snap[0].forEach(cat => {
        catsArray.push({ id: cat.id, ...cat.data() })
      }),
      snap[1].forEach(cat => {
        catsArray.push({ id: cat.id, ...cat.data() })
      })
    ])
      .then(() => commit('setCats', catsArray))
  }
}

export default {
  namespaced: true,
  state,
  actions,
  mutations,
}

这是我的 vue 文件的一部分,它在屏幕上显示数据。我省略了不必要的部分。
要打开所有带有 Prop 的路线,然后单击类别会将路由器发送到下一个类别。 (这样我可以使用浏览器功能向后移动)。
销售.vue
<template>
...........
<v-col
  v-for="catOrProduct in catOrProducts"
  :key="catOrProduct.id"
  @click.prevent="leftClickProd($event, catOrProduct)"
  @contextmenu.prevent="rightClickProd($event, catOrProduct)">

....ViewMagic....
</v-col>
............
</template>

<script>
.........
  props: {
    catIdFromUrl: {
      type: String,
      default: undefined
    }
  },

  computed: {
    // https://stackoverflow.com/questions/40322404/vuejs-how-can-i-use-computed-property-with-v-for
    ...mapState('catOrProducts', ['catOrProducts']),
  },

  watch: {
    '$route.path'() { this.bindCatsWithProducts(this.catIdFromUrl) },
  },

  mounted() {
    this.bindCatsWithProducts(this.catIdFromUrl)
  },

  methods: {
    leftClickProd(event, catOrProd) {
      event.preventDefault()
      if (typeof (catOrProd.parentCat) === 'string') { // when parentCat exists we have a Category entry
        this.$router.push({ name: 'sale', params: { catIdFromUrl: catOrProd.id } })
        // this.bindCatsWithProducts(catOrProd.id)
      } else {
        // ToDo: Replace with buying-routine
        this.$refs.ProductMenu.open(catOrProd, event.clientX, event.clientY)
      }
    },
  }
</script>

编辑 24.09.2020
我已将绑定(bind)逻辑更改为
const mutations = {
  setCatProd(state, val) {
    state.catOrProducts = val
  },
}

const actions = {
async bindCatsWithProducts({ commit, dispatch }, CatID) {
    const contain = CatID || 'nC'
    const arr = []

    catsColl.where('parentCat', '==', contain).orderBy('name', 'asc')
      .onSnapshot(snap => {
        snap.forEach(cat => {
          arr.push({ id: cat.id, ...cat.data() })
        })
      })

    productsColl.where('cats', 'array-contains', contain).orderBy('name', 'asc')
      .onSnapshot(snap => {
        snap.forEach(prod => {
          arr.push({ id: prod.id, ...prod.data() })
        })
      })

    commit('setCatProd', arr)
  },
}

这很有效,因为当我在后端更改某些内容时数据会更新。
但是现在我每次发生变化时都会添加一个对象。例如,我改变了价格。现在我明白了:
Two products with identical ID's
我不知道为什么,因为我有 key Vue 中设置的字段。渲染的代码是:
<v-container fluid>
  <v-row
    align="center"
    justify="center"
  >
    <v-col
      v-for="catOrProduct in catOrProducts"
      :key="catOrProduct.id"
      @click.prevent="leftClickProd($event, catOrProduct)"
      @contextmenu.prevent="rightClickProd($event, catOrProduct)"
    >
      <div>
        <TileCat
          v-if="typeof(catOrProduct.parentCat) == 'string'"
          :src="catOrProduct.pictureURL"
          :name="catOrProduct.name"
        />
        <TileProduct
          v-if="catOrProduct.isSold"
          :name="catOrProduct.name"
          ... other props...
        />
      </div>
    </v-col>
  </v-row>
</v-container>
为什么这不能正确更新?

最佳答案

来自 Vuefire docs ,这是您仅使用 Firebase 订阅更改的方式:

// get Firestore database instance
import firebase from 'firebase/app'
import 'firebase/firestore'

const db = firebase.initializeApp({ projectId: 'MY PROJECT ID' }).firestore()

new Vue({
  // setup the reactive todos property
  data: () => ({ todos: [] }),

  created() {
    // unsubscribe can be called to stop listening for changes
    const unsubscribe = db.collection('todos').onSnapshot(ref => {
      ref.docChanges().forEach(change => {
        const { newIndex, oldIndex, doc, type } = change
        if (type === 'added') {
          this.todos.splice(newIndex, 0, doc.data())
          // if we want to handle references we would do it here
        } else if (type === 'modified') {
          // remove the old one first
          this.todos.splice(oldIndex, 1)
          // if we want to handle references we would have to unsubscribe
          // from old references' listeners and subscribe to the new ones
          this.todos.splice(newIndex, 0, doc.data())
        } else if (type === 'removed') {
          this.todos.splice(oldIndex, 1)
          // if we want to handle references we need to unsubscribe
          // from old references
        }
      })
    }, onErrorHandler)
  },
})
我通常会避免任何不必要的依赖,但根据您的目标,您可以使用 Vuefire 添加另一层抽象,或者如您所说,做一些“魔术绑定(bind)”。
import firebase from 'firebase/app'
import 'firebase/firestore'

const db = firebase.initializeApp({ projectId: 'MY PROJECT ID' }).firestore()

new Vue({
  // setup the reactive todos property
  data: () => ({ todos: [] }),
  firestore: {
    todos: db.collection('todos'),
  },
})

关于javascript - Vue,火库 : how to display LIVE data after merging collections,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63945128/

相关文章:

javascript - VueJS v-for 对象不显示键

javascript - 删除 VuetifyJS v-tabs 组件的 header

javascript - 如何从 javascript 创建 jQuery Mobile 按钮?

android - Gradle DSL 方法未找到 : 'classpath()' after adding firebaseui libraries

java - 在应用 order by 之前操作 Firebase 文档字段中存储的值

自定义 token 的 firebase 弹出窗口

vue.js - 有没有办法在 Nuxt 中 Hook 页面重新加载?

javascript - 如果只有一张图像,请禁用 Royalslider 中的项目符号

javascript - 如果用户单击子元素,如何检索属性值?

javascript - 检查超时是否已清除?