Making ClickOutSide Directive in Vue
Nowadays, in most of the web applications, we create and use have a lot of UI component such as open a popup, dropdown and close it when the user clicks outside it.
In some of the popup, we may have very complex UI or functionality which we may not 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 popup but it becomes very difficult to maintain popups when we have two or more popups in web app likes to maintain the variables or writing 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.
Let’s create the Project
First, you need to create a Vue project using vue-cli. If you don’t have installed vue-cli then you can install it from this link.
Before we create our custom directive, let’s create a page with a two button that shows and hides a popup dialogs.
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 below code and run the app.
That’s simple right. we have just put two buttons which open different popup when you click on it.
So, when you run the code and click on any of the buttons you will see the below output.
Currently, I have put the directive code in App.vue file which is not the ideal way to do it. In your project create one folder and put all the directive code in that folder along with this.
Here, I haven’t use any variables or js code in 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.
Now, Let’s understand the directive so you can also create your own directive and customize it as per your requirement.
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 query.
References : https://tahazsh.com/detect-outside-click-in-vue