How to reload date after a Vuejs action

Asked

Viewed 59 times

1

My list remains the same after deleting an item, only refreshes when I hit F5 on screen. I’ve tried using componentKey, but it only works when I click 2 clicks.

Follow current component code:

<template>
  <table>
    <thead>
      <tr>
        <td>ID</td>
        <td>Nome</td>
        <td>Raça</td>
        <td>#</td>
      </tr>
    </thead>
    <tbody>
      <tr v-for="d in dog.data" :key="d.id">
        <td>{{ d.id }}</td>
        <td>{{ d.titulo }}</td>
        <td>{{ d.conteudo }}</td>
        <td><button @click="deleteDog(d.id)">Deletar</button></td>
      </tr>
    </tbody>
  </table>
</template>

<script>
import api from "../services/api";

export default {
  data() {
    return {
      dog: [],
    };
  },
  mounted() {
    api.get("dogs").then((response) => (this.dog = response.data));
  },
  methods: {
    deleteDog(id) {
      api.delete("dog/" + id);
    },
  },
};
</script>

2 answers

1


You can remove the element from the list dog after calling the API, using simple array methods.

Within the method deleteDog:

deleteDog(id) {
  api.delete("dog/" + id).then(() => {
     // localiza o indice do elemento no array
     const index = this.dog.findIndex(dog => dog.id === id)  

     if (index >= 0) {
        // remove apenas ele do array
        this.dog.splice(index, 1) 
     }
  });
}

Or, call the API again, which will bring up-to-date data. It may not be very elegant to make a call every time you delete an element, but it can be done:

deleteDog(id) {
  api.delete("dog/" + id).then(() => {
     // chama novamente a API com os dados atualizados
     api.get("dogs").then((response) => (this.dog = response.data));
  });
},

How Vue works with the View concept depending on the state, change the value of dog will cause the refresh only of the component that has this state, without having to tighten F5.

  • It worked, thank you very much.

0

Your array is being populated at the time the view is mounted, so any changes to the api that occur after that will not be reflected in your array of results. For changes in the view to occur, you must update (delete the specific item) your array every time the deleteDog method is triggered.

Vue is reactive, so if you modify the array, it will reload the element automatically, the problem is that the deleteDog method updates only the data source.

There are ways these updates can be done automatically, depending on the framework or packages you use. Meteor, for example, keeps a copy of the database in the browser, which is synchronized with the original database, so all changes are reflected in the view for everyone who is watching, but you search more about it later.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.