我刚刚开始学习vuex,无法删除项目。我可以直接在组件中删除项目。
deleteCar (cars, id) {
this.$http.delete('http://localhost:3000/cars/' + cars.id)
.then(() => {
this.cars.splice(id, 1)
})
}
在vuex中,我有:
state: {
car: {},
cars: []
},
mutations: {
ADD_CAR (state, car) {
state.car = car
},
GET_CARS (state, cars) {
state.cars = cars
}
},
actions: {
createCar({commit}, car) {
axios.post('http://localhost:3000/cars', car)
.then(() => {
commit('ADD_CAR', car)
})
},
loadCars({commit}) {
axios.get('http://localhost:3000/cars')
.then(res => {
const cars = res.data
commit('GET_CARS', cars)
})
}
}
我要删除项目的组件中的代码:
<div class="card mb-3" v-for="(car, i) in cars" :key="i">
<div class="card-header">
Cars name: {{ car.carName }}
</div>
<div class="card-body">
<h5 class="card-title">Country: {{ car.country }}</h5>
<p class="card-text">Year of manufacture: {{ car.carYear }}</p>
<button class="btn btn-primary mb-5" @click="deleteCar(car, i)">Delete Car</button>
</div>
</div>
我可以加购车。但是不能删除
答案 0 :(得分:4)
为简化起见,简化的答案。
在模板中:
<button @click="deleteCar(car)">Delete Car</button>
组件中的方法:
deleteCar(car) {
this.$store.commit('DELETE_CAR', car);
}
商店中的变异:
DELETE_CAR(state, car) {
var index = state.cars.findIndex(c => c.id == car.id);
state.cars.splice(index, 1);
}
答案 1 :(得分:0)
我看到您正在将Axios与Vue一起使用,因此您的请求.delete
要求已删除,但是在.then
中您应该执行与删除或拼接无关的操作
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);
)
}
在.then
中,由于.delete
请求已从JSON数据中删除了该部分,您需要执行删除操作
答案 2 :(得分:0)
您要进行更改以删除汽车
这是您的方法
deleteCar (cars, id) {
this.$http.delete('http://localhost:3000/cars/' + cars.id)
.then(() => {
this.cars.splice(id, 1)
})
}
您希望将其更改为deleteCar(cars, id)
而不是deleteCars({commit}, id)
所以您的行动将会
deleteCar ({commit}, id) {
this.$http.delete('http://localhost:3000/cars/' + id)
.then(() => {
commit('DELETE_CAR', id)
})
}
您有一个突变DELETE_CAR
DELETE_CAR(state, id){
index = state.cars.findIndex(car => car.id == id)
state.cars.splice(index, 1)
}