'Closing a Vue.js component on click
I'm currently working on a small project, but I'm stuck and can't find the correct answer that I'm looking for so maybe someone can help me out here.
So what i have are 2 components where the parent component calls the child component like so:
<open-pokemon
v-if="open"
:pokemon-name="clickedPokemon"
:type="clickedPokemonType"
>
</open-pokemon>
The openPokemon component also got a closing button to close the component what I want to do is to delete the component from the dom, but it still needs to be rendered when the openPokemon gets called again.
Anyway here is the closing method:
closePokemon: function (e) {
document.getElementById(e).classList.add('close');
self = this;
self.$destroy();
self.$el.parentNode.removeChild(self.$el);
}
And here is my html for that:
<div id="pokemon-single" class="c-pokemon__single-open" :class="type">
<div class="flex justify-end">
<button @click="closePokemon('pokemon-single')" class="c-pokemon__single-close">
X
</button>
</div>
</div>
While this will work i can't seem to figure out why I can't rerender the component when i call it again in the parent component. Any help would be appreciated. If you need more information let me know.
Solution 1:[1]
Solution
- Emit a
closeevent from the child when the close button is clicked. - Listen for the close event in the parent and set
opento false.
Child (OpenPokemon)
<template>
<div id="pokemon-single" class="c-pokemon__single-open" :class="type">
<div class="flex justify-end">
<button @click="close" class="c-pokemon__single-close">X</button>
</div>
</div>
</template>
<script>
export default {
methods: {
close () {
this.$emit('close')
}
}
}
</script>
Parent
<template>
<div>
<open-pokemon
v-if="open"
:pokemon-name="clickedPokemon"
:type="clickedPokemonType"
@close="open = false"
/>
</div>
</template>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cam |
