Home > Software engineering >  Closing a Vue.js component on click
Closing a Vue.js component on click

Time:03-17

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"  :>
                    <div >
                        <button @click="closePokemon('pokemon-single')" >
                            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.

CodePudding user response:

Solution

  • Emit a close event from the child when the close button is clicked.
  • Listen for the close event in the parent and set open to false.

Child (OpenPokemon)

<template>
  <div id="pokemon-single"  :>
    <div >
      <button @click="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>
  • Related