小码问答,有问必答!

在element-ui的子菜单中el-menu-item添加自己的@click事件后,点击就收回了,咋办?

<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>


WEB前端

收藏

2个回答

我要回答

  • author
    牛叔叔 2024-12-05 15:00

    在 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 时不会关闭子菜单,你可以尝试以下步骤:

    1. 确保 clkStudent 方法中没有任何会导致菜单关闭的逻辑。

    2. 移除 .native 修饰符。

    3. 如果 .prevent 修饰符导致问题(尽管通常不应该),尝试移除它,并在 clkStudent 方法中使用 event.stopPropagation()(如果确实需要阻止冒泡)。

    但是,更简单的做法是:

    vue复制代码


    <el-menu-item v-for="student in c.students" :key="c.id+'-'+student.id" :index="c.id+'-'+student.id" @click="clkStudent(student.id, $event)">

    {{student.name}}

    </el-menu-item>

    然后在 clkStudent 方法中:

    javascript复制代码


    methods: {

    clkStudent(studentId, event) {

    // 阻止默认行为(如果有的话,通常不需要)

    // event.preventDefault();



    // 阻止事件冒泡(如果确实需要,但通常不应该影响菜单的显示)

    // event.stopPropagation();



    // 你的逻辑代码

    console.log('Clicked student ID:', studentId);

    // ...

    }

    }

    注意,通常你不需要在 clkStudent 方法中调用 event.preventDefault() 或 event.stopPropagation(),因为 el-menu-item 的默认行为就是触发你的 @click 事件而不会关闭菜单。如果问题仍然存在,请检查其他可能影响菜单行为的代码或样式。


    • author
      nellac 2021-04-30 18:30

      题主您好,请问这个问题解决了吗?我也碰到了相同的问题。