LoginSignup
0
0

More than 1 year has passed since last update.

vuejs 배열에서 항목삭제하기

Posted at

기존방식같기는 하지만 부모컴포넌트에서 자식컴포넌트에 이벤트를 전달하는 방식

HomeVue.vue
<template>
  <v-container>
    <v-col>
      <ListView
        :todolist="todolist"
        @statusControl="statusControl"
        @deleteItem="deleteItem"
        @editItem="editItem"
      />
    </v-col>
    <v-col>
      <ListAdd @listAdd="listAdd" />
    </v-col>
  </v-container>
</template>

<script>
import ListAdd from '@/components/ListAdd.vue';
import ListView from '@/components/ListView.vue';
export default({
  name: 'HomeView',
  components: {
    ListAdd,
    ListView

  },
  data() {
    return {
      todolist : [],
    }
  },
  methods : {
    deleteItem(index){
      this.todolist.splice(index,1)
    },
  }
});
</script>

Vuex store 를 활용해서 배열삭제하기

  1. 삭제할 배열을 담을 items[]선언한다.
  2. mutation 에서 delItem(state, index) 함수를 만든다,.
  3. mutation 에서 만든 함수를 action 애서 불러온다.
import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
Vue.config.devtools = true;
export default new Vuex.Store({
  namespaced: true,
  state: {
    //data 삭제할 아이템을 담는 배열 선언
    items: [],
  },
  mutations: {
    delItem(state, index) {
      state.items.splice(index, 1);
    },
  },
  actions: {
    delItem({ commit }, id) {
      commit("delItem", id);
    },
  },
});

실제 장바구니에 담긴 상품을 삭제하는 component

CartList.vue
<template>
  <div>
    <div class="header-cart header-dropdown">
      <ul class="header-cart-wrapitem">
        <template v-for="(item, index) in items">
          <li :key="index" class="header-cart-item">
            <div class="header-cart-item-img" @click="delItem(index)">
              <img :src="item.image" alt="IMG" />
            </div>
          </li>
        </template>
      </ul>     
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters } from "vuex";

export default {
  computed: {
    ...mapState(["items"]),
    ...mapGetters(["totalPrice", "totalQty"]),
  },
  created() {},
  methods: {
//스토어에 접근해서 dispatch를 통해서 스토어에 있는 함수 delItem을 불러온다.
    delItem(index) {
      this.$store.dispatch("delItem", index);
    },
  },
};
</script>
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0