【问题标题】:How delete an item using vuex?如何使用 vuex 删除项目?
【发布时间】:2019-05-03 09:56:00
【问题描述】:

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

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>

我可以添加汽车并获取汽车。但不能删除

【问题讨论】:

标签: vue.js axios vuex


【解决方案1】:

我看到你正在使用 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 数据中删除了该部分

【讨论】:

  • 我只想从数组中删除项目。但是想用 axios 做到这一点。我可以用 axios 获取数据,可以发布。但是删除有问题
【解决方案2】:

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

这是你的方法

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

您需要将其更改为 deleteCars({commit}, id) 而不是 deleteCar(cars, 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)
}

【讨论】:

  • 在突变 DELETE_CAR 中,我会在该索引之后放置一个 if 语句,因为如果找不到汽车 findIndex 返回 -1 哪个拼接将用于从数组末尾删除元素 - 可能不是效果你想要的。
【解决方案3】:

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

在模板中:

<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);
 }

【讨论】:

    猜你喜欢
    • 2018-10-30
    • 2021-06-21
    • 2021-03-30
    • 2019-02-05
    • 2011-09-24
    • 2011-04-12
    • 2016-12-19
    • 2021-10-19
    • 1970-01-01
    相关资源
    最近更新 更多