How delete an item using vuex?
You want to commit a mutation to delete the car
Here is your method
deleteCar (cars, id) {
this.$http.delete('http://localhost:3000/cars/' + cars.id)
.then(() => {
this.cars.splice(id, 1);
});
}
Instead of deleteCar(cars, id)
you will want to change it to deleteCars({commit}, id)
So your action would be
deleteCar ({commit}, id) {
this.$http.delete('http://localhost:3000/cars/' + id)
.then(() => {
commit('DELETE_CAR', id);
});
}
And you have a mutation DELETE_CAR
DELETE_CAR(state, id){
index = state.cars.findIndex(car => car.id == id);
state.cars.splice(index, 1);
}
A simplified answer for clarity.
in the template:
<button @click="deleteCar(car)">Delete Car</button>
method in the component:
deleteCar(car) {
this.$store.commit('DELETE_CAR', car);
}
mutation in the store:
DELETE_CAR(state, car) {
var index = state.cars.findIndex(c => c.id == car.id);
state.cars.splice(index, 1);
}
I see that you're using Axios with Vue, so your request .delete
requesst that delete already but in .then
you should do something not related to delete or splice,
deleteCar (cars) {
this.$http
.delete('http://localhost:3000/cars/' + cars.id', { data: payload })
.then(
//here write what you want after delete
res => console.log(res);
)
}
in .then
you do what you need after delete because of .delete
request already deleted that part from your JSON data