<el-submenu index="1"> <template slot="title"><i class="el-icon-message"></i>在校班级</template> <el-menu-item-group v-for="group in onstudyclasses"> <template slot="title">{{group.title}}</template> <template v-for="c in group.classes"> <el-submenu :index="group.id+'-'+c.id" > <template slot="title">{{c.title}}</template> <el-menu-item v-for="student in c.students" :index="c.id+'-'+student.id" @click.native.prevent="clkStudent(student.id)">{{student.name}}</el-menu-item> </el-submenu> </template> </el-menu-item-group> </el-submenu>
在 Element UI 的
el-menu
组件中,当你为el-menu-item
添加点击事件时,如果点击事件导致菜单项被收起(即子菜单关闭),这通常是因为点击事件触发了默认的菜单项导航行为,或者是因为事件冒泡导致的。在你的代码中,你使用了.native.prevent
修饰符,这通常用于在组件上监听原生事件并阻止默认行为,但在el-menu-item
上可能不是最佳实践,因为el-menu-item
已经是一个处理点击事件的组件。首先,你应该移除
.native
修饰符,因为el-menu-item
不是一个原生 HTML 元素,而是一个 Vue 组件。.native
用于监听组件根元素的原生事件,但在这种情况下,你应该直接监听组件提供的点击事件。其次,
.prevent
修饰符用于阻止事件的默认行为。在el-menu-item
上,这可能会阻止菜单项的正常导航(如果有的话),但在这个场景中,你更可能是想要阻止事件冒泡到父菜单项,从而避免关闭子菜单。然而,.prevent
通常不会阻止事件冒泡,而是阻止默认行为。要阻止事件冒泡,你需要使用事件对象的方法event.stopPropagation()
。但是,在 Element UI 的
el-menu-item
中,通常不需要手动阻止事件冒泡,因为点击el-menu-item
应该会触发你的@click
事件而不会关闭菜单(除非你的事件处理函数中有代码导致菜单关闭)。如果你的clkStudent
方法中有任何逻辑可能导致菜单行为异常,你应该检查该方法的内容。不过,为了确保点击
el-menu-item
时不会关闭子菜单,你可以尝试以下步骤:确保
clkStudent
方法中没有任何会导致菜单关闭的逻辑。移除
.native
修饰符。如果
.prevent
修饰符导致问题(尽管通常不应该),尝试移除它,并在clkStudent
方法中使用event.stopPropagation()
(如果确实需要阻止冒泡)。但是,更简单的做法是:
然后在
clkStudent
方法中:注意,通常你不需要在
clkStudent
方法中调用event.preventDefault()
或event.stopPropagation()
,因为el-menu-item
的默认行为就是触发你的@click
事件而不会关闭菜单。如果问题仍然存在,请检查其他可能影响菜单行为的代码或样式。题主您好,请问这个问题解决了吗?我也碰到了相同的问题。