Problem description:
A menu will appear when an Icon clicks, click any area outside the menu area to close.
What is to solve the above problems elegantly?
- Use vue as much as possible to solve the problem
- Interact with native objects as little as possible
- Clean and easy to understand code
Problem solving ideas:
- Determine the display and hiding of the menu through Vue's v-show command.
- Determine whether it should be closed by the global click event of Document
- Several problems need to be solved elegantly:
- The click event is prohibited. Use VUE @ to solve the problem, please refer to the code below
- Elegantly and safely remove global event listening (only listen when the menu pops up)
Adding event to document
HTML
<template> <div class="dir"> <!-- Button,Pay special attention@Used to prohibit message bubbles --> <span title="Sorting" @="onSortClick()" class="icons">Button</span><br/> <!-- menu v-showSet variables showSortmenu,styleThe content should be written from the beginning! Not sure if it isBUG,Not initialstyleIncorrect display --> <ul class="menu" v-show="showSortmenu" style="display: block;"> <li sort="title"> <span>title</span> </li> <li sort="lastModify"> <span>Last modified time</span> </li> <li sort="free"> <span>Custom sorting</span> </li> </ul> </div> </template>
JavaScript
<script> export default { name: "demo2", data() { return { showSortmenu: false }; }, props: {}, methods: { //Receive button click event @, bubbles are prohibited onSortClick: function() { //Set the bool value, = !; // Pay special attention to this, only when the menu is displayed will the global click event be listened to when the global click event is displayed //And, to set the method to: vue, you cannot throw it outside the export code segment. //Remember who the corresponding instance of the variable `this` is if () { ("click", ); } }, //Global listening to click event onGlobalClick(e) { //Judge the className of the control that is clicked globally, the difference is to click outside the menu if ( != "sort_by_menu") { = false; //Be careful here!!! Be sure to remove the monitoring event! ! ! ! ! ("click", ); } } }, mounted() {}, }; </script>
Summarize
The above is the idea of Vue to implement the display/hidden layer (plus global click event) introduced to you by the editor. I hope it will be helpful to everyone!