vue3 triggers the callback function of the right mouse button
Just add @contextmenu="contextmenu" to the tag
<div @contextmenu="contextmenu" class="contextmenu"></div>
Show the menu we defined
Remove the default menu of the browser
- By preventDefault api
(); //The default triggering event behavior is preventDefault() Canceled
- Define a menu page
<div class="fixed-box" :style="fixedBoxStyleObject" v-show="isShowMenu" > <span>Delete the chat</span> </div>
This page is bound to the isShowMenu variable to display or not display the menu. The fixedBoxStyleObject variable is used to set the menu position
- Define the triggered callback function
const contextmenu = (e) => { (); //The default trigger event behavior was canceled by preventDefault() = + 'px' = + 'px' = true }
Click elsewhere menu disappears
Generally, we use setting focus and losing focus trigger events to complete this function, such as:
Set the focus when right-clicking, then when clicking other places, the focus loss event will be triggered. Just call the callback function
- Optimize template part
<div tabindex="-1" class="fixed-box" :style="fixedBoxStyleObject" v-show="isShowMenu" @blur="isShowMenu = false" ref="fixedBoxRef"> <span>Delete the chat</span> </div>
- Optimize the scipt part
const contextmenu = (e) => { (); //The default trigger event behavior was canceled by preventDefault() = + 'px' = + 'px' = true setTimeout(() => { () },1) }
tips:
- Since the div itself cannot get focus, the focus can be obtained after setting the tabindex
- The reason for setting a timer is that it takes time to display the dom from not to display, and it must be displayed before it can get the focus.
CSS part
.fixed-box{ position: fixed; color: black; padding: 8px; width: fit-content; background-color: #F8F8F8; } .contextmenu{ width:300px; height:300px; margin: 100px auto; }
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.