如何使用 vuex 删除项目?

Ник*_*лов 8 vue.js axios vuex

刚开始学习vuex,不能删除item。我可以直接在组件中删除项目。

deleteCar (cars, id) {
        this.$http.delete('http://localhost:3000/cars/' + cars.id)
          .then(() => {              
              this.cars.splice(id, 1)
          })
      }
Run Code Online (Sandbox Code Playgroud)

在 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)
        })
    }
  }
Run Code Online (Sandbox Code Playgroud)

我想删除项目的组件中的代码:

<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>
Run Code Online (Sandbox Code Playgroud)

我可以加车和取车。但是不能删除

TJ *_*ems 9

你想提交一个突变来删除汽车

这是你的方法

deleteCar (cars, id) {
        this.$http.delete('http://localhost:3000/cars/' + cars.id)
          .then(() => {              
              this.cars.splice(id, 1)
          })
      }
Run Code Online (Sandbox Code Playgroud)

而不是deleteCar(cars, id)你想把它改成deleteCars({commit}, id)

所以你的行动是

deleteCar ({commit}, id) {
        this.$http.delete('http://localhost:3000/cars/' + id)
          .then(() => {              
              commit('DELETE_CAR', id)
          })
      }
Run Code Online (Sandbox Code Playgroud)

你有一个突变 DELETE_CAR

DELETE_CAR(state, id){
 index = state.cars.findIndex(car => car.id == id)
 state.cars.splice(index, 1)
}
Run Code Online (Sandbox Code Playgroud)


And*_*rew 6

为了清楚起见,简化了答案。

在模板中:

<button @click="deleteCar(car)">Delete Car</button>
Run Code Online (Sandbox Code Playgroud)

组件中的方法:

 deleteCar(car) {
    this.$store.commit('DELETE_CAR', car);
 }
Run Code Online (Sandbox Code Playgroud)

商店突变:

 DELETE_CAR(state, car) {
    var index = state.cars.findIndex(c => c.id == car.id);
    state.cars.splice(index, 1);
 }
Run Code Online (Sandbox Code Playgroud)