Two way binding of Dialogs: Vue

Two-way binding gives our app a mechanism to share data between components and their templates.

Neha Soni
Easy coding
3 min readNov 6, 2020

--

In a Vue application, we use the v-model many times or I can say the v-model is an essential pillar of Vue projects. This v-model is doing what we called two-way binding.

Have you ever used this two-way binding for dialog boxes?

In most cases, we use dialogs in the same component we are working on because passing data to dialogs’ components and handle opening and closing functionality from dialog’s component is strenuous sometimes.

But this is not the solution we can follow always because sometimes we need to divide code into components and keep a dialog box in a separate component that can be a need.

Let’s get started to explore this functionality.

Note- I am using the Vuetify framework for styling but the concept of this will remain the same for any framework or with a non-framework.

First, create a component named Home.vue and drop the below code inside it.

Now, create a component DialogBox.vue (This is going to contain dialog functionality apart from the parent component).

What is happening inside this code?

We create a variable of name dialog in the parent component and bind this to the child component of the name DialogBox.

This two-way binding does two things-

  1. Set a specific property to the element.
  2. Listen for any change event to the element.

In the context of point 2, we are emitting an event, “close” from the child component, and listening to this into the parent component via “@close”.

So when we click on the button the v-model binding will do two things-

  1. Listen to the dialog opening event (when clicking on the “open dialog” button) in the child component(DialogBox.vue).
  2. Listen dialog closing event (when clicking on the “close” button of the dialog box) in the parent component (Home.vue).

Here is the response, how this code should work-

Isn’t it a pretty simple way to manage code by keeping dialog boxes in separate components?

Thanks for reading.

--

--

Neha Soni
Easy coding

Hi there! I'm passionate about sharing knowledge. If you've found my articles useful, you can buy me a coffee! :-D (https://www.buymeacoffee.com/nehasoni988)