如何使用vuex删除项目? [英] How delete an item using vuex?

查看:80
本文介绍了如何使用vuex删除项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I just started learning vuex and can`t delete item. I can delete item directly in the component.

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

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

Code in component where i wanna delete item:

<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>

我可以添加汽车并获得汽车.但是不能删除

I can add car and get cars. But can`t delete

推荐答案

您要进行更改以删除汽车

You want to commit a mutation to delete the car

这是您的方法

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

您希望将其更改为 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)
}

这篇关于如何使用vuex删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆