I
I
Intelix2022-01-24 19:28:17
Vue.js
Intelix, 2022-01-24 19:28:17

Why does removing an element from an array not work?

I have a component in which, with the help of v-for, several blocks with titles and additional information are displayed.

On the wrapper of the block, a click handler that calls a function in which it is checked whether there is an element (clicked on) with the same id in the array, if so, delete it, otherwise add it.

On the block with additional infoy hangs v-if with a condition whether there is an element with such id in an array.

I need to make it so that the block with the info is shown if it is clicked on and disappears if it is clicked a second time. (for each block, several can be opened at once)

But for some reason, only the first block works correctly, when you click on the subsequent ones, their id is not removed from the array.
https://codesandbox.io/s/blissful-https-zg4tg?file...

Answer the question

In order to leave comments, you need to log in

3 answer(s)
0
0xD34F, 2022-01-24
@Intelix

Works. There is just nothing to remove. What makes you think that the positions of the elements and their id in the elementData and selectedElArr arrays will match? The index should not be passed to the method, but calculated independently inside:

methods: {
  toggleElement(id) {
    const index = this.selectedElArr.indexOf(id);
    if (index !== -1) {
      this.selectedElArr.splice(index, 1);
    } else {
      this.selectedElArr.push(id);
    }
  },
  ...

@click="toggleElement(data.id)"

E
eRKa, 2022-01-24
@kttotto

Error in method logic showElement.
You always add id to the end of the list, but you remove id by the position index of the div in the list, although it is not certain that the id will be in this place.
For example, you clicked on the 3rd element, then on the second, it will be selectedElArr = [2, 1], then you click on the 3rd to close it and the method wants to delete selectedElArr[2], but there is not even such an element. Well, etc.
It makes more sense to add selectedElArr[index]=trueand remove selectedElArr[index]=false, based on the order of the divs in the list. Well, check it out later

if (!!this.selectedElArr[index]) {
 this.selectedElArr[index] = false;
} else {
 this.selectedElArr[index] = true;
}}

Or one line
this.selectedElArr[index] = !this.selectedElArr[index];

If not rely on, then I would add a field data.isOpened(isActive, isVisible, etc.) and start from it, it seems to me more reliable.

E
Eugene, 2022-01-24
@cyber-jet

Something is completely complicated with you, it's vue!

<template>
  <div
    class="element"
    v-for="data in elementData"
    :key="data.id"
    @click="data.show = !data.show"
  >
    <h1>Клик</h1>
    <div 
      v-if="data.show" 
      class="elementInfo"
    >
      <h5>{{ data.name }}</h5>
      <p>{{ data.id }}</p>
    </div>
  </div>
</template>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question