SoFunction
Updated on 2025-04-11

Sample code to implement dynamic right-click menu in Vue

In front-end development, a custom right-click menu is a common way of interaction that can provide users with more functional options. In this article, we will explore how to implement a dynamic right-click menu in Vue that can dynamically adjust its display position according to the user's click position, ensuring that the menu is always within the visible area of ​​the browser window.

Achieve the goal

  • A custom menu is displayed when right-clicking on a page.
  • The menu is dynamically positioned according to the click location.
  • Make sure the menu does not exceed the visible area of ​​the browser window. (Optimized beyond the top or bottom of the window)

Implementation steps

1. Create a Vue component template

First, write the template part of the Vue component:

<template>
  <div v-if="visible">
    <a-menu class="contextmenu" :style="style" @click="handleClick">
      <a-menu-item v-for="item in list" :key="">
        <span>{{  }}</span>
      </a-menu-item>
    </a-menu>
  </div>
</template>

In this template, usev-ifThe command controls the display and hide of the menu and uses:styleBinding the dynamic style of the menu.

2. Write component scripts

Next is the scripting part of the component:

&lt;script&gt;
export default {
  name: "ContextMenu",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    list: {
      type: Array,
      required: true,
      default: () =&gt; [],
    },
  },
  data() {
    return {
      left: 0,
      top: 0,
      target: null,
    };
  },
  computed: {
    style() {
      return {
        left:  + "px",
        top:  + "px",
      };
    },
  },
  created() {
    const clickHandler = () =&gt; ();
    const contextMenuHandler = (e) =&gt; {
      ();
      (e);
    };
    ("click", clickHandler);
    ("contextmenu", contextMenuHandler);
    this.$emit("hook:beforeDestroy", () =&gt; {
      ("click", clickHandler);
      ("contextmenu", contextMenuHandler);
    });
  },
  methods: {
    closeMenu() {
      this.$emit("update:visible", false);
    },
    setPosition(e) {
      // Get the width and height of the menu      const menu = (".contextmenu");
      const menuHeight = ;
      // Get the visible height of the window      const windowHeight = ;

       = ;

      // Calculate the upper position of the menu      if ( + menuHeight &gt; windowHeight) {
        const top =  - menuHeight;
        if (top &lt; 0) {
           = 0; // Make sure the menu does not exceed the top        } else {
          // If the bottom of the menu exceeds the bottom of the window           = top;
        }
      } else {
        // If the bottom of the menu does not exceed the bottom of the window         = ;
      }

       = ;
    },
    handleClick({ key }) {
      const _component = ((item) =&gt;  === key)[0]
        .component;
      if (_component) {
        this.$emit("contextMenuClick", _component, key);
      }
      ();
    },
  },
};
&lt;/script&gt;

Detailed explanation

setPosition method

setPositionThe method is used to dynamically adjust the position of the menu according to the position the user clicks, ensuring that the menu is always in the visible area.

setPosition(e) {
  // Get the width and height of the menu  const menu = (".contextmenu");
  const menuHeight = ;
  // Get the visible height of the window  const windowHeight = ;

   = ;

  // Calculate the upper position of the menu  if ( + menuHeight &gt; windowHeight) {
    const top =  - menuHeight;
    if (top &lt; 0) {
       = 0; // Make sure the menu does not exceed the top    } else {
      // If the bottom of the menu exceeds the bottom of the window       = top;
    }
  } else {
    // If the bottom of the menu does not exceed the bottom of the window     = ;
  }

   = ;
}
  • Add up:pass + menuHeightCalculate the position at the bottom of the menu, if it is greater thanwindowHeight, it means that the menu exceeds the bottom of the window and needs to be adjusted.
  • Subtraction:pass - menuHeightAdjust the menu position to the top of the mouse click position to make sure the menu does not exceed the bottom of the window.
  • clientY: The vertical coordinate of the mouse click position, relative to the viewport.
  • offsetHeight: The height of the menu element, including the height of the content, the inner margins and the border.

Event handling

existcreatedLifecycle hook, addedclickandcontextmenuEvent listener.

created() {
  const clickHandler = () => ();
  const contextMenuHandler = (e) => {
    (e);
  };
  ("click", clickHandler);
  ("contextmenu", contextMenuHandler);
  this.$emit("hook:beforeDestroy", () => {
    ("click", clickHandler);
    ("contextmenu", contextMenuHandler);
  });
}
  • clickHandler: Close the menu when clicking on the page.
  • contextMenuHandler: When right-clicking, the default right-click menu behavior is blocked and the menu position is set according to the click location.

Style section

<style lang="scss" scoped>
.contextmenu {
  position: fixed;
  z-index: 1000;
  border-radius: 4px;
  border: 1px lightgrey solid;
  box-shadow: 4px 4px 10px lightgrey !important;
}
</style>

Summarize

Through the above code, a dynamic right-click menu is implemented. This menu can dynamically adjust its display position according to the user's click position, ensuring that the menu is always within the visible area of ​​the browser window. This implementation can improve the user experience and make the application more friendly and easy to use.

This is the article about the example code for implementing the dynamic right-click menu in Vue. For more related Vue dynamic right-click menu content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!