Article

Making ClickOutSide Directive in Vue

Last updated 
Jul 24, 2020
 min read

ClickOutSide Directive in Vue

Nowadays, in most of the web applications, we create and use a lot of UI components such as opening a popup, or dropdown and closing it when the user clicks outside it.

In some of the popups, we may have very complex UI or functionality that we might not be able to find in any frontend CSS framework like Bootstrap, foundation, etc. so at last we need to create our own popup component.

We can create our own custom popups but it becomes very difficult to maintain popups when we have two or more popups in the web app to maintain the variables or write JS code to hide and show popups.

There are many ways to create popups in Vue, but a good, simple one is to create a custom directive.

Creating a Project

First, you need to create a Vue project using vue-cli. If you do not have vue-cli installed, then you can install it from here.

Creating Popup Buttons

Before we create our custom directive, let’s create a page with two buttons that show and hide a popup dialog.

You can take a look at what we’re going to build on CodePen:

We’re going to do all of our work in a single App.vue file.

So in the App.vue file add the below code and run the app.

That’s simple, right? We have just put two buttons that open different popups when you click on them.

So, when you run the code and click on any of the buttons you will see the below output.

I have currently put the directive code in the App. Vue file, which is not the ideal way to do it. In your project, create a folder and put all the directive code in that folder along with this.

Here, I haven’t used any variables or JS code in the Vue component to show/hide the popups. So it will be less burdensome for us to maintain the variables/js code in the component when we have three or more popups in one single screen.

Popup screen

Implementing the Directive

Now, let’s understand the directive so you can also create your own directive and customize it as per your requirements.

I have mentioned all the understanding of each line in the comment of the file.

That’s it. Our ClickOutSide directive is built which we can use across all the components of the Vue app.

Thanks for reading the blog.

Let me know if you have any doubts or queries.

Also Read: Creating a Custom Masking Input Textbox in Vue

Authors

Ravi Patel

Technical Lead
I am a Frontend developer with proficiency in Angular and Vuejs with more than 6 years of experience. I have done Bachelors engineering in Information Technology. I am experienced in making web apps using Angular, Vuejs, Reactjs, Javascript, Webpack, Gulp, Html, CSS, AWS. I love to explore new Frontend technologies and get used to it.

Tags

No items found.

Have a project in mind?

Read