简体   繁体   中英

Vue.js and Firestore replace array on db change

I am using Vue.js and Firestore. I have some buttons that are dynamic.

When I edit a button and push the changes to the db it adds to my array instead of replacing it.

If I refresh the page everything works correctly.

I am assuming there is a way to make the array reactive

here is my code:

<template>
  <v-app id="app">
    <Navbar />
    <router-view :key="$route.fullPath"></router-view>
    <v-speed-dial
      v-model="fab"
      fixed
      bottom
      right
      direction="top"
      transition="scale-transition"
    >
      <v-btn
        slot="activator"
        v-model="fab"
        color="blue-grey darken-2"
        dark
        fab
      >
        <v-icon>directions_run</v-icon>
        <v-icon>close</v-icon>
      </v-btn>
      <span v-for="tag in tags" :key="tag.icon">
        <v-btn
        fab
        dark
        small
        :color="tag.color"
        >
          <v-icon>{{tag.icon}}</v-icon>
        </v-btn>
      </span> 
    </v-speed-dial>
  </v-app>
</template>

<script>
import Navbar from '@/components/layout/Navbar'
import db from '@/firebase/init'

export default {
  name: 'App',
  data() {
    return {
      fab: false,
      tags: []
    }
  },
  components: {
    Navbar: Navbar
  },
  created() {
    let tagRef = db.collection('tags').orderBy('order')
    tagRef.onSnapshot(snapshot => {
        snapshot.docChanges().forEach(snap => {
          let tag = snap.doc
          this.tags.push(tag.data())
        })
    })
  }
}
</script>

You have two ways. First: find and replace your outdated tag. Or clear array and re-add all items with new one.

Second way may looks like:

 created() {
 let self = this// you can't use "this" inside onSnapshot
    let tagRef = db.collection('tags').orderBy('order')
    tagRef.onSnapshot(snapshot => {
     self.tags.length = 0
          snapshot.forEach(snap => {
          self.tags.push(tag.data())
        })
    })
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM