0

By clicking on an array element, I add it to the end of the new array

<div class="grid">
  <div class="cell" v-for="item in posts" :key="item">
    <img :class="{active: item.isActive}" :src="item.url" alt width="293px" height="293px" @click="choosePost(item)" />
  </div>
</div>

    choosePost(item) {
    item.isActive = !item.isActive
    if (item.isActive == true) {
      this.selectedPosts.push(item)
    } else this.selectedPosts.splice(????, 1)
  console.log(this.selectedPosts)
},

I want to make it so, that when I click on an element again, it will be removed from the array. I tried using the splice method but I don’t understand how can I get the index of the selected item. Please tell me how to do this?

2 Answers 2

2

You can get index in v-for:

<div class="grid">
  <div class="cell" v-for="(item, index) in posts" :key="item">
    <img
      :class="{ active: item.isActive }"
      :src="item.url"
      width="293px"
      height="293px"
      @click="choosePost(item, index)"
    />
  </div>
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

skr.sh/v1volChtKlu only works with the first element of the old array. I can not understand why
0

You can use indexes in an v-for loop look:

<div class="grid">
  <div class="cell" v-for="(item, index) in posts" :key="item">
    <img :class="{active: item.isActive}" :src="item.url" alt width="293px" height="293px" @click="choosePost(item, index)" />
  </div>
</div>

choosePost(item, index) {
    item.isActive = !item.isActive
    if (item.isActive == true) {
      item["posIndex"] = index;
      this.selectedPosts.push(item)
    } else {
      let pos = this.selectedPosts.map(function(e) { return e.posIndex; }).indexOf(index);
      this.selectedPosts.splice(pos, 1);
    }
  console.log(this.selectedPosts)
},

5 Comments

skr.sh/v1volChtKlu only works with the first element of the old array. I can not understand why
how does item looks like can you show me the strucutre=
skr.sh/v1vNoSKD5yD everything is fine with the first element. property "isActive" at next elements change to false, but that elements don't remove at the array
try this code out. you slice the wrong index. if you select for example the second item, your index will be 1. and that item is gonna be stored in selectedPosts. But when u try to slice it, you slice the item at index 1 but selectedPosts contain only 1 value so his index is 0 not 1. I have written an one-line code to get the correct index of that element
select the 3rd element and then un-select it. pos should be 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.