SoFunction
Updated on 2025-04-13

vue3 realizes the right mouse button to display the menu, click other places to disappear the problem

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
  &lt;div class="fixed-box" :style="fixedBoxStyleObject" v-show="isShowMenu" &gt;
    &lt;span&gt;Delete the chat&lt;/span&gt;
  &lt;/div&gt;

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) =&gt; {
  ();   //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
  &lt;div tabindex="-1" class="fixed-box" :style="fixedBoxStyleObject" v-show="isShowMenu" @blur="isShowMenu = false" ref="fixedBoxRef"&gt;
    &lt;span&gt;Delete the chat&lt;/span&gt;
  &lt;/div&gt;
  • Optimize the scipt part
const contextmenu = (e) =&gt; {
  ();   //The default trigger event behavior was canceled by preventDefault()   =  + 'px'
   =  + 'px'
   = true
  setTimeout(() =&gt; {
      ()
  },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.