简体   繁体   中英

How can I make delete function real-time using firebase / vue.js

<v-tooltip top>
  <template v-slot:activator="{ on, attrs }">
    <v-btn
      plain
      small
      color="red"
      v-bind="attrs"
      v-on="on"
      @click="removeData(project.id)"
      ><v-icon>mdi-delete</v-icon></v-btn
    >
  </template>
  <span>delete project</span>
</v-tooltip>

I am a beginner . This code above is the delete button with function removeData(project.id) , and this code below shows the function:

removeData(doc) {
  if (confirm("Are you sure ?")) {
    db.collection("projects")
      .doc(doc)
      .delete()
      .then(() => {
        console.log("Document successfully deleted!");
      });
  }
},

It worked successfully, but I don't know how to make it real-time with Firestore. I know only how to make it real-time when I add something as you see in the code below:

created() {
  db.collection("projects").onSnapshot((res) => {
    const changes = res.docChanges();
    changes.forEach((change) => {
      if (change.type === "added") {
        this.projects.push({
          ...change.doc.data(),
          id: change.doc.id,
        });
      }
      if (change.type === "removed") {
        //code goes here
      }
    });
  });
},

If this.projects is an array, you can remove the delete item from it with:

if (change.type === "removed") {
   this.projects = this.projects.filter(item => item.id !== change.doc.id);
}

Also see the MDN documentation on Array.filter .

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