Home > Enterprise >  Vue.js - Why can't I delete all items from an array?
Vue.js - Why can't I delete all items from an array?

Time:11-08

I got a parent component (a form) broken down into child components to handle different types of input data. The data is pre-populated from an API. If a user makes a new selection or changes some data in the child components, I want to emit it up to the parent component so I can use it in a form submit event and pass this new data to the database/API.

The above logic works on updates, however, if the user wants to delete an item (by selecting the "X" button in the screenshot shown below), I need to also update the form result's array and not include the "deleted" item. The form Results array kind of works, but for some reason I can't delete remove the cards from the UI:

screenshot

The parent component is passing down the form value props to the child and child is emitting the updates back up to parent:

<ISOAdminDivForm />
    <ISOAdminDivFormName />
        <ISOAdminDivFormNameItem />

Can someone check out my codesandbox demo and help me figure out why I can't dynamically delete the "cards" from the UI?

https://codesandbox.io/s/foundation-form-names-forked-tvwpu?file=/src/components/ISOAdminDivFormName.vue

CodePudding user response:

I managed to have something working. It was actually simpler than I thought originally since you included many files (more than needed for a minimal, reproducible example).

Basically, it boils down to properly updating the divisionLanguages data property.

To make it simpler, I removed the formValues data since I think is just confusing and redundant with divisionLanguages.data.

As I said in my comments, to update a reactive list in Vue, you need to use Array.splice.

So your deleteItem method will need to find the index of the item to remove then splice the array with said index:

deleteItem(id) {
  const elementIndex = this.divisionLanguages.data.findIndex(
    (x) => x.P_uniqueID === id
  );
  this.divisionLanguages.data.splice(elementIndex, 1);
  this.$emit("languages", this.divisionLanguages.data);
}

Here is the forked sandbox: https://codesandbox.io/s/foundation-form-names-forked-b7sy2?file=/src/components/ISOAdminDivFormName.vue

  • Related