VueJS: Write Your Own Dropdown Menu

Tram Ho

I. Preparation:

Create a new vue-app:

Basic Config:

  1. Babel.
  2. Esint.

Oke. Run the web:

II. Idea:

Basically, I will write a dropdown-menu , quite similar to that of bootstrap (because I do not focus on the UI, so I only fully function it, you have time to try to improve):

dropdown-bootstrap menu 4

Check Document Dropdown Menu of Bootstrap Here!

The problem here is, I do not use a third external Library.

Okey, make some noises!

II. Perform:

1. Directory tree:

Because only create DropdownMenu component as List-Item , my directory structure will basically look like Vue CLI, so I’ll show the changed part:

2. UI:

I will do the CSS quickly, you can use the built-in CSS of Bootstrap loaded if you do not want to do the UI .

File app.vue :

File DropdownMenu/index.vue :

File DropdownMenu/Item.vue :

3. Logic code:

At DropdownMenu/index.vue I will have the props :

  • Use an passed id to support the DOM and distinguish between multi dropdown-menu .
  • There are prop arrays for passing item to the dropdown-menu .

File Home.vue :

Inside DropdownMenu/index.vue :

  • There isOpen variable is the Dropdown-menu open switch ( true is open, false is closed).
  • Item.vue to Item.vue 1 function : closeDropdown performs our Dropdown-menu closure from the Item inside.

File DropdownMenu/Item.vue :

In theory, click button will open and close our DropdownMenu , in addition, click each Item will also close Dropdown . If I want to perform a certain job in Item , I pass the function to the item in the arrays and use the methods in Item.vue to recall that job.

In addition, DropdownMenu must be closed when we click outside of it. At this time, I use window.addEventListener('click', ...) to detect each click and check if I am clicking on DropdownMenu or not?

For now, I will use the hook :

  • created to addEventListener .
  • beforeDestroy to removeEventListener .

File DropdownMenu/index.vue :

The code document.getElementById('your-id).contains( will return true if we click on an HTML object that is a child of your-id (prop) that we passed above.

Now, I will create one more DropdownMenu next to check the case of multi dropdown-menu :

File Home.vue :

It worked, perfectly!

I would like to share my repos, everyone please clone and comment for me.

Link github: Here!

Thank you, Mr. Trần Đại Sơn for giving me an opinion on the eventListener section. Thanks for everyone who has read your article.

Share the news now

Source : Viblo