반응형
vuex를 사용하여 항목을 삭제하는 방법
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>
나는 차를 추가할 수 있고 차를 얻을 수 있다.그러나 삭제할 수 없습니다.
당신은 차를 삭제하기 위해 변이를 저지르려고 한다.
여기 당신의 방법이 있습니다.
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);
}
알기 쉽게 대답할 수 있습니다.
템플릿에서 다음을 수행합니다.
<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);
}
Vue와 함께 Axios를 사용하시는군요..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 데이터에서 해당 부품을 이미 삭제했습니다.
언급URL : https://stackoverflow.com/questions/53571167/how-delete-an-item-using-vuex
반응형
'source' 카테고리의 다른 글
| vuejs는 상위 구성 요소에서 하위 구성 요소로 모델을 전달하고 변환을 허용합니다. (0) | 2022.08.03 |
|---|---|
| 다른 스레드의 주 스레드에서 실행 중인 코드 (0) | 2022.08.03 |
| POSIX 소켓을 플러시하는 방법이 있습니까? (0) | 2022.08.03 |
| '안드로이드'를 어떻게 고치죠?Network On Main Thread Exception'? (0) | 2022.08.03 |
| 롬복은 어떻게 작동하나요? (0) | 2022.08.01 |