Skip to content
Advertisement

How to delete particular array by selecting checkbox and delete array in Vuejs?

<script>
import { datalist } from "./datalist";
export default {
  name: "HelloWorld",
  components: {},
  data() {
    return {
      items: datalist,
    };
  },
  methods: {
    deleteEvent(id) {
      this.items = this.items.filter((e) => e.id !== id);
    },
  },
};
</script>
My data...
export const datalist = [
  { id: 1, val: "11", kk: "potter" },
  { id: 2, val: "22", kk: "james" },
  { id: 3, val: "55", kk: "limda" },
  { id: 4, val: "77", kk: "stepen" }
];
 
  <div>
    <div v-for="item in items" :key="item.id">
      <b>{{ item.id }}.</b> &nbsp;&nbsp;&nbsp;
      <router-link :to="{ name: 'UserWithID', params: { id: item.id } }">
        {{ item.kk }}
      </router-link>
      <input type="checkbox" :value="item.id" />
      <button @click="deleteEvent(item.id)">Delete</button>
    </div>
  </div>

My complete code;- https://codesandbox.io/s/wild-flower-rssg0?file=/src/components/datalist.js

I want to delete the array item, When user click on checkbox beside each item. and then click on delete button then the array item record need to be deleted.

But now i am getting as, Directly if I click on delete button, i am able to delete the array. But that should happen only after the checkbox click and then delete button.

For this process, I have taken click event in button and added a method to delete array record but its not working…. Can u please help me what is wrong with the code…

Advertisement

Answer

You should maintain an array of items to delete. Bind the checkbox to this array so that if the checkbox is checked, the item ID is added to this array. Then, simply add a delete button somewhere to delete all selected items.

See example here: https://codesandbox.io/s/elated-lake-ws2wn

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement