Detailed explanation of the error when using Element-ui NavMenu submenu to generate recursively

Detailed explanation of the error when using Element-ui NavMenu submenu to generate recursively

When the submenu of the navigation bar is generated recursively, the menu can be generated normally, but when the mouse is hovered, a certain (mouseenter) event will be called cyclically, resulting in an error in the end

Processing

Note: In version 2.13.2, you only need to set the attribute of the submenu: popper-append-to-body="false" to avoid this problem.

The error message is as follows:

Uncaught RangeError: Maximum call stack size exceeded.
at VueComponent.handleMouseenter (index.js:1)
at invokeWithErrorHandling (vue.js:1863)
at HTMLLIElement.invoker (vue.js:2188)
at HTMLLIElement.original._wrapper (vue.js:7547)
at VueComponent.handleMouseenter (index.js:1)
at invokeWithErrorHandling (vue.js:1863)
at HTMLLIElement.invoker (vue.js:2188)
at HTMLLIElement.original._wrapper (vue.js:7547)
at VueComponent.handleMouseenter (index.js:1)
at invokeWithErrorHandling (vue.js:1863)

Test code

Version:

  • vue: v2.6.11
  • element-ui: 2.13.0
<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title></title>
  <!-- Import style -->
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css" rel="external nofollow" >
 </head>
 <body>

  <div id="root">
   <el-menu mode="horizontal">
    <template v-for="(menu,index) in menus">
     <sub-menu v-if="menu.children && menu.children.length" :key="index" :item="menu"></sub-menu>
     <el-menu-item v-else :index="menu.path" :key="index">{{ menu.title }}</el-menu-item>
    </template>
   </el-menu>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <!-- Import component library-->
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
  <script type="text/javascript">
   Vue.component('sub-menu', {
    props: ['item'],
    template: `
     <el-submenu :index="item.path">
      <template slot="title">
       {{item.title}}
      </template>
      <template v-for="(child,index) in item.children">
       <sub-menu v-if="child.children" :item="child" :key="index"></sub-menu>
       <el-menu-item v-else :key="index" :index="child.path">
        {{child.title}}
       </el-menu-item>
      </template>
     </el-submenu>
    `
   })

   let vm = new Vue({
    el: '#root',
    data() {
     return {
      menus: [{
       title: 'My Workbench',
       path: '2',
       children: [{
         title: 'Option 1',
         path: '2-1'
        },
        {
         title: 'Option 2',
         path: '2-2',
        },
       ],
      },{
       title:'Background Management',
       path:'3'
      }]
     }
    },
    components: {}
   })
  </script>
 </body>
</html>

Error Analysis

Observe the recursively generated navigation bar code and error code:

 handleMouseenter: function(e) {
                    var t = this
                      , i = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : this.showTimeout;
                    if ("ActiveXObject" in window || "focus" !== e.type || e.relatedTarget) {
                        var n = this.rootMenu
                          , r = this.disabled;
                        "click" === n.menuTrigger && "horizontal" === n.mode || !n.collapse && "vertical" === n.mode || r || (this.dispatch("ElSubmenu", "mouse-enter-child"),
                        clearTimeout(this.timeout),
                        this.timeout = setTimeout(function() {
                            t.rootMenu.openMenu(t.index, t.indexPath)
                        }, i),
                        this.appendToBody && this.$parent.$el.dispatchEvent(new MouseEvent("mouseenter")));//Error code}
                },

I guess it's because the event bubbling or sinking causes the element to repeatedly dispatch and receive mouseenter events, resulting in a state similar to an infinite loop. Due to time constraints, I didn't go into it in depth. I'll check the root cause later when I have time (if I remember...)

When the mouse moves into the menu, the handleMouseenter method is triggered, but because appendToBody is true, the mouse enter event is dispatched again, and then returns to this method, resulting in an infinite loop. appendToBody is a calculated property, so why is appendToBody true? Look at the code:

{
 name: 'ElSubmenu',
    componentName: 'ElSubmenu',
 props:{
  popperAppendToBody: {
         type: Boolean,
         default: undefined   
        }
    },
    computed:{
  appendToBody() {
        return this.popperAppendToBody === undefined     
          ? this.isFirstLevel //When popperAppendToBody is not explicitly specified, calculate this value: this.popperAppendToBody;
      },
      isFirstLevel() {
        let isFirstLevel = true;
        let parent = this.$parent;
        while (parent && parent !== this.rootMenu) {
        
        //Calculate whether the current menu is the first level.
        //It seems to be OK, because the code has specified that the current component name is componentName: 'ElSubmenu', but during debugging, it was found that the value of componentName is Undefined, so no matter which level it is, the final result is isFirstLevel = true 
          if (['ElSubmenu', 'ElMenuItemGroup'].indexOf(parent.$options.componentName) > -1) {
            isFirstLevel = false;
            break;
          } else {
            parent = parent.$parent;
          }
        }
        return isFirstLevel;
      }
 }
}

As for why Vue did not collect this parameter when registering the component, we still need to look at the source code. The lunch break is over, and I have to continue to code... I will analyze it again when I have time...

Processing

Add an attribute to el-submenu: popper-append-to-body="true false" to explicitly specify appendToBody as false

Special apologies:

The previous processing method was written incorrectly. It was written as: popper-append-to-body="true". Therefore, even if this attribute is added, an error is still reported. I apologize for this!

This is the end of this article about the detailed explanation of the error when using recursive generation of Element-ui NavMenu submenu. For more relevant content about recursive generation of Element-ui NavMenu submenu, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Solution for highlighting the vue+element navigation bar
  • Element-Ui component NavMenu specific use of navigation menu
  • Solve the problem that the navigation menu is highlighted in the wrong position after refreshing the Vue project
  • Solve the problem of highlighting the NavMenu navigation menu in elementui (solve multiple situations)

<<:  Detailed example of MySQL data storage process parameters

>>:  VMware Workstation 14 Pro installs CentOS 7.0

Recommend

Comparison of the efficiency of different methods of deleting files in Linux

Test the efficiency of deleting a large number of...

Detailed explanation of JS browser storage

Table of contents introduction Cookie What are Co...

Tutorial on deploying nginx+uwsgi in Django project under Centos8

1. Virtual environment virtualenv installation 1....

React Router 5.1.0 uses useHistory to implement page jump navigation

Table of contents 1. Use the withRouter component...

Docker installs the official Redis image and enables password authentication

Reference: Docker official redis documentation 1....

MySQL 8.0.12 Simple Installation Tutorial

This article shares the installation tutorial of ...

How to install phabricator using Docker

I am using the Ubuntu 16.04 system here. Installa...

JavaScript Canvas draws dynamic wireframe effect

This article shares the specific code of JavaScri...

How to solve the high concurrency problem in MySQL database

Preface We all know that startups initially use m...

How to decrypt Linux version information

Displaying and interpreting information about you...

React introduces antd-mobile+postcss to build mobile terminal

Install antd-mobile Global import npm install ant...

MySQL 8.0.25 installation and configuration tutorial under Linux

The latest tutorial for installing MySQL 8.0.25 o...

How to create a view on multiple tables in MySQL

In MySQL, create a view on two or more base table...