Reputation: 566
I have a simple popup component that get's called on a click event in some places in my app. The popups get created on click and are pushed in an array, that is later forEach-ed and displayed so that when the user clicks on a button multiple times multiple popups are displayed. The success ones disappear and the red ones disappear once someone clicks on the X, I achieve that by splicing them from the array, but if a user generated 5 popups and clicks the X the next popup gets closed, not the one that the user has clicked on, so it seems that I am not targeting the specific popup order in the array but the next, how can I properly target the exact clicked modal so that it gets closed and not the one that is next in line, what am I doing wrong here? How should I splice the array properly so that I target the exact pushed modal and not the rest?
Here is my code:
<template>
<div class="main">
<div
v-for="item in array"
:key="item.id"
:class="['popUp', `popUp--type--${item.popUpTypeType}`]"
>
<div class="popUp-side">
<p class="exclamation-mark">!</p>
</div>
<h5 class="popUp-message">{{item.message}}</h5>
<div class="popUp-side">
<p class="closing-x" @click="closeMessage" v-if="item.popUpTypeType === 'danger'">X</p>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'popUp',
data: () => ({
array:[],
}),
methods: {
removepopUpType() {
var self = this;
var id = Math.round( Math.random()*1e13 );
var index = self.array.map(x => {
return x.id;
}).indexOf(id);
self.array.splice(index, 1);
},
callpopUpType(obj){
var newpopUpType = {
popUpTypeType: obj.type,
message: obj.message,
id: obj.id
};
if(obj.type === 'success'){
setTimeout(this.removepopUpType, 2000)
}
this.array.push(newpopUpType);
},
closeMessage() {
this.removepopUpType()
},
},
created() {
this.$root.$on('call-popUp', this.callpopUpType);
},
destroyed(){
this.$root.$off('call-popUp', this.callpopUpType);
}
}
</script>
Upvotes: 0
Views: 956
Reputation: 14053
There is quite a bit of unusual code in the example, so I may be missing something, but couldn't you just pass the item
to the method.
<p
v-if="item.popUpTypeType === 'danger'"
class="closing-x"
@click="closeMessage(item)"
>X</p>
and then
closeMessage(item) {
const index = this.array.indexOf(item);
if (index >= 0) this.array.splice(index, 1)
},
Upvotes: 1