SoFunction
Updated on 2025-04-03

Two ways to close the current pop-up page

Close the current pop-up page in Vue can be achieved in the following two ways:

1. Use the Close button to trigger the Close event

Add a close button to the pop-up component and call the method to close the pop-up in the click event. For example:

<template>
  <div class="modal">
    <div class="modal-content">
      <span class="close" @click="closeModal">×</span>
      <p>Pop-up content</p>
    </div>
  </div>
</template>
<script>
export default {
  methods: {
    closeModal() {
      this.$emit('close');
    }
  }
}
</script>

Listen to the closing event in the parent component and set the pop-up display status to false. For example:

<template>
  <div>
    <button @click="showModal = true">Open pop-up window</button>
    <modal v-if="showModal" @close="showModal = false"></modal>
  </div>
</template>
<script>
import Modal from './';
export default {
  components: {
    Modal
  },
  data() {
    return {
      showModal: false
    }
  }
}
</script>

2. Use the route guard to close the pop-up window

Add a beforeRouteLeave route guard to the route that opens the pop-up window, and close the pop-up window when leaving the route. For example:

const router = new VueRouter({
  routes: [
    {
      path: '/modal',
      component: Modal,
      beforeRouteLeave(to, from, next) {
        this.$emit('close');
        next();
      }
    }
  ]
});

Listen to the closing event in the parent component and call the method to close the pop-up window in the closing event. For example:

<template>
  <div>
    <button @click="showModal = true">Open pop-up window</button>
    <modal v-if="showModal" @close="showModal = false"></modal>
  </div>
</template>
<script>
import Modal from './';
export default {
  components: {
    Modal
  },
  data() {
    return {
      showModal: false
    }
  }
}
</script>

Both of the above methods can realize the function of closing the current pop-up page. The specific method to use depends on the project needs and personal habits.

Summarize

This is the end of this article about two ways to close the current pop-up page of Vue. For more related content of Vue closing the current pop-up page, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!