How to close model from a button using vue.js ?
Last Updated :
18 Jan, 2021
Improve
This article will tell us about how to close a modal from a button using vue.js. To close a modal using vue.js you can use the click event i.e. @click to trigger change in modal visibility. So, whenever the close button is pressed the @click method will trigger the function associated with the action ( here, hiding the modal ).
Syntax
Step-1:
Add @click=”$emit(‘close’)” property to the close button of the modal.
<button type="button" class="close" @click="$emit('close')"> X </button>
Step-2:
In the component where modal is used add close modal and open modal properties in data
data () { return { isModalVisible: false, }; }, methods: { showModal() { this.isModalVisible = true; }, closeModal() { this.isModalVisible = false; } }, };
Sample Code:
Creating the modal component
Javascript
export default { name: 'modal' , }; |
Using the modal component in App.vue
Javascript
import modal from './components/modal.vue' ; export default { name: 'app' , components: { modal, }, data () { return { isModalVisible: false , }; }, methods: { showModal() { this .isModalVisible = true ; }, closeModal() { this .isModalVisible = false ; } }, }; |
Output
