Code example of integrating element-plus el-menu and vue-router

router.js

It's just simple code using vue-router for demonstrating. Nothing is special.

import { createRouter, createWebHashHistory } from 'vue-router'
import NavView from '../views/NavView.vue'
import TagsView from '../views/TagsView.vue'
import SearchView from '../views/SearchView.vue'
import HomeView from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      name: 'nav',
      component: NavView,
      children: [
        {
          path: '',
          component: HomeView
        },
        {
          path: 'search',
          component: SearchView,
        },
        {
          path: 'tags',
          component: TagsView
        },
      ]
    },
  ]
})

export default router

The menu uses routes defined above.

<template>
  <el-menu :router="true" :default-active="$route.path">
    <el-menu-item index="/">Home</el-menu-item>
    <el-menu-item index="/tags">Tag Management</el-menu-item>
    <el-menu-item index="/search">Search</el-menu-item>
  </el-menu>
  <RouterView />
</template>

Notice:

  • :router="true" tells el-menu to support vue-router.
  • :default-active="$route.path" tells el-menu that by default a menu-item is activated according to the path.
  • index attribute of el-menu-item should correspond to the routes defined by router.js.
Posted on 2023-07-04