来一起做个后台管理用的轻量级路由 + 菜单吧

简介: Vue3 的后台管理的项目想要做个菜单的话,一般会使用 VueRouter 设置路由,然后用UI库的菜单组件(比如 el-menu)设置各种属性,然后还需要考虑权限等问题。 这样做虽然很灵活,但是对于简单项目就有点麻烦。那么我们能不能简化一下操作,只设置一次,就可以实现菜单、路由外加权限的功能呢?

Vue3 的后台管理的项目想要做个菜单的话,一般会使用 VueRouter 设置路由,然后用UI库的菜单组件(比如 el-menu)设置各种属性,然后还需要考虑权限等问题。 这样做虽然很灵活,但是对于简单项目就有点麻烦。那么我们能不能简化一下操作,只设置一次,就可以实现菜单、路由外加权限的功能呢?

技术栈 / 基础工具

  • vue3,script setup
  • 动态组件、异步组件
  • window.history
  • el-menu、el-tabs

在线演示

https://naturefw.gitee.io/nf-rollup-ui-controller 可以来这里看看效果,好吧其实也没啥特别的,看效果也没啥区别,只是使用的时候比较很方便。

源码

https://gitee.com/naturefw/nf-rollup-ui-controller

思路

首先模仿 VueRouter 设置一个路由,这里简化一下,只考虑单层路由。然后再设置上菜单需要的属性。 因为要做二级菜单,所以再设置一个分组信息,另外再加上图标(icon)的设置,这样基本就够用了。 然后设置页面布局,根据设置绑定菜单(el-menu),加载组件即可。

设置路由和菜单

import { defineAsyncComponent } from'vue'
import home from'./home.vue'
import { Loading, Connection, Edit, FolderOpened } from'@element-plus/icons'
// 基础路径
const baseUrl = '/nf-rollup-ui-controller'
/**
 * 一级菜单,设计包含哪些二级菜单
 */
const group = [
  {
    id: 1,
    title: '基础控件',
    icon: FolderOpened,
    children: [
      'base_html',
      'base_ui',
      'base_transmit',
      'base_item'
    ]
  },
  {
    id: 2,
    title: '复合控件',
    icon: FolderOpened,
    children: [
      'nf_form',
      'nf_find',
      'nf_grid',
      'nf_button',
      'nf_crud'
    ]
  }
]
/**
 * 二级菜单,设置路径、标题、图标和加载的组件
 */
const routes = {
  base_html: {
    path: '/base-html',
    title: '原生HTML',
    icon: Edit,
    component: () =>import('./ui/base/c-01html.vue')
  },
  base_ui: {
    path: '/base-ui',
    title: 'UI库组件',
    icon: Edit,
    component: () =>import('./ui/base/c-02UI.vue')
  },
  base_transmit: {
    path: '/base-transmit',
    title: '传声筒',
    icon: '',
    component: () =>import('./ui/base/c-03transmit.vue')
  } 
}


  • 设置基础路径
    本地开发可以使用根目录,但是项目发布后可能无法使用根目录了,这时候就需要设置一个基础路径,以应对只能使用二级目录的情况。
  • 预留权限接口
    这里的 children 只是记录了路由的 key ,而不是完整的路由配置,这样设计是为了以后可以方便的加上权限,可以按照权限过滤掉没有权限的路由(模块)的key,这样加权限就方便多了。
  • 图标的设置方式
    因为 element-plus 使用“组件”形式的图标,所以还得用动态组件的方式来加载图标,需要在设置的地方引入需要的图标,然后设置到菜单的属性里面,这样就可以实现图标的设置了。
  • 组件的设置
    采用异步组件(defineAsyncComponent)来加载需要的组件,设置方式和 VueRouter 保持一致。

设计加载组件和刷新的处理方法

然后设计两个函数,一个是加载组件的,一个是页面刷新后根据 url路径 加载组件的函数。

// 加载路由指定的组件
const getComponent = (key) => {
  const route = routes[key]
  if (route) {
    // 设置标题
    document.title = route.title
    // 设置url地址
    window.history.pushState(null, null, baseUrl + route.path)
    // 返回组件
    return defineAsyncComponent(route.component)
  } else {
    return home
  }
}
// 刷新时依据url加载组件
const refresh = (cb) => {
  const path = window.location.pathname
  if (path === '/' || path === baseUrl) {
    // 首页
  } else {
    const tmp = path.replace(baseUrl, '')
    // 加载组件
    for (const key in routes) {
      const route = routes[key]
      if (route.path === tmp) {
        if (typeof cb === 'function'){
          cb(key)
        }
        break
      }
    }
  }
}
// 导出配置和函数
export {
  group,
  routes,
  getComponent,
  refresh
}
  • 设置标题和 URL 地址
    点击菜单,加载组件,顺便设置一下浏览器的标题和 URL 的路径。 虽然现在浏览器都是标签的形式,没有太大的空间显示标题,不过设置一下标题也不麻烦。 然后用 window.history.pushState 设置一下浏览器的 URL 路径,这样设置不会导致浏览器向服务器请求页面。
  • 刷新自动加载组件
    刷新页面后如果不做设置的话,是不会依据 URL 加载对应的组件的,所以还需要我们写个函数处理一下。 首先获取 URL 的路径(pathName),然后到路由设置里面查找对应的组件,然后加载即可。 这里做了一个回调函数,可以更方便一些。

绑定菜单

做一个菜单的组件,比如叫做 menu.vue,引入上面的设置,然后绑定到 el-menu 上面。

<el-menu
    class="el-menu-vertical-demo"
    @select="select"
    background-color="#6c747c"
    text-color="#fff"
    active-text-color="#ffd04b"
  >
    <el-sub-menu v-for="(item, index) in group"
      :key="index"
      :index="item.id"
    >
      <template #title>
        <component
          :is="item.icon"
          style="width: 1.5em; height: 1.5em; margin-right: 8px;"
        >
        </component>
        <span>{{item.title}}</span>
      </template>
      <el-menu-item v-for="(key, index) in item.children"
        :key="index"
        :index="key">
        <template #title>
          <component
            :is="routes[key].icon"
            style="width: 1.5em; height: 1.5em; margin-right: 8px;"
          >
          </component>
          {{routes[key].title}}
        </template>
      </el-menu-item>
    </el-sub-menu>
  </el-menu>

使用动态组件(component)加载图标 ,其他的按照 el-menu 的要求进行设置即可,这样一个简单的二级菜单就做好了。

然后设置一个组件属性,用于传递选择的菜单。

const props = defineProps({
  events: Object
})
const events = props.events
// 二级菜单被选中
const select = (index, indexPath) => {
  events.currIndex = index  // 路由的key
}

设计页面布局

采用 el-container 做页面布局,左面是菜单,右面加载对应的组件。

<el-container>
    <el-aside width="200px">
      <!--菜单-->
      <nf-menu :events="events" />
    </el-aside>
    <el-main>
      <!--二级导航-->
      <component
        :is="getComponent(events.currIndex)"
      >
      </component>
    </el-main>
  </el-container>

引入配置和函数,设置选择的菜单的对象,这样就可以了。

const events = reactive({
  currIndex: ''
})
refresh((key) => {
  events.currIndex = key
})

加上权限过滤

设计权限的时候,需要标注可以访问哪些菜单,也就是组件,然后设置好对应的菜单(路由)的 key 即可。绑定的地方换成过滤后的数组即可。

实现多tab标签页

上面的方法是实现了“单页”的方式,点一个菜单加载一个组件,再点一个菜单,替换掉原来的组件。 如果想做成 tab 标签页的形式要怎么做呢? 其实也很简单,我们只需要增加一个 数组 (Set,tabs) 用于存放点击过的菜单的key,然后依据 tabs 绑定 el-tabs 即可。

  • 设置容器和监听
const tabs = reactive(newSet([])) // 点击过且没有关闭的二级菜单,做成动态tab标签
// 监听当前路由,设置 tabs
    watch(() =>currentRoute.key, (key) => {
      tabs.add(key)
      const route = this.routes[key] ?? {title: '首页', path: '/'}
      // 设置标题
      document.title = route.title
      // 设置url地址
      window.history.pushState(null, null, this.baseUrl + route.path)
    })
  • 绑定el-tabs
<el-tabs
    v-model="currentRoute.key"
    type="card"
  >
    <el-tab-pane
      v-for="key in tabs"
      :key="key"
      :label="routes[key].title"
      :name="key"
    >
     <template #label>
        <span>{{routes[key].title}} &nbsp;
          <circle-close-filled
            style="width: 1.0em; height: 1.0em; margin-top: 8px;"
            @click.stop="removeTab(key)" />
        </span>
      </template>
      <component :is="routerControl[key]">
      </component>
    </el-tab-pane>
  </el-tabs>

这样就可以了。

把零散的代码封装成 函数库 + 组件

基本功能测试通过,回顾一下代码,还是有一些麻烦,我们可以进一步封装一下:

  • 路由+菜单的函数库
  • 菜单组件(nf-menu)
  • 路由视图——单页(router-view)
  • 路由视图——tabs(router-view-tabs)

这样封装之后就方便多了,另外顺便重构一下代码。

路由的函数库

我们可以用 ES6 的 class 来定义,实现各种基础功能。

import { defineAsyncComponent, reactive, watch, inject } from'vue'
const flag = Symbol('nf-router-menu___')
/**
 * 一个简单的路由
 * @param {*} baseUrl 基础路径
 * @param {*} routes 路由设置
 * * {
 * *   base_html: { // 路由的 name
 * *     path: '/base-html',
 * *     title: '原生HTML',
 * *     icon: Edit,
 * *     component: () => import('./ui/base/c-01html.vue')
 * *   },
 * *   其他路由设置 
 * * }
 * @returns 
 */
class Router {
  constructor (info) {
    // 设置当前选择的路由
    this.currentRoute = reactive({
      key: ''
    })
    this.baseUrl = info.baseUrl // 基础路径,应对网站的二级目录
    this.home = info.home // 默认的首页
    this.group = info.group // 一级菜单,分组,设置包含的二级菜单(路由)
    this.routes = info.routes // 路由设置,二级菜单
    /**
     * 'key', 'key' // 保存路由的key(name)
     */
    this.tabs = reactive(newSet([])) // 点击过且没有关闭的二级菜单,做成动态tab标签
    // 把路由里的组件转换一下
    this.routerControl = {}
    this.setup()
  }
  /**
   * 初始化设置
   */
  setup = () => {
    // 监听当前路由,设置 tabs
    watch(() =>this.currentRoute.key, (key) => {
      if (key !== 'main' ) this.tabs.add(key)
      const route = this.routes[key] ?? {title: '首页', path: '/'}
      // 设置标题
      document.title = route.title
      // 设置url地址
      window.history.pushState(null, null, this.baseUrl + route.path)
    })
    // 把路由里的组件转换一下
    for (const key inthis.routes) {
      const r = this.routes[key]
      this.routerControl[key] = defineAsyncComponent(r.component)
    }
  }
  // 加载路由指定的组件
  getComponent = () => {
    if (this.currentRoute.key === '') {
      returnthis.home
    } else {
      const route = this.routes[this.currentRoute.key]
      if (route) {
        // 返回组件
        return defineAsyncComponent(route.component)
      }
    }
  }
  // 删除tab
  removeTab = (key) => {
    // 转换为数组,便于操作
    const arr = Array.from(this.tabs)
    if (arr.length === 1) {
      // 只有一个tab,删除后激活桌面
      this.tabs.delete(key)
      this.currentRoute.key = 'home'
      return
    }
    // 判断是否当前tab,如果是当前tab,激活左面或者右面的tab
    if (this.currentRoute.key === key) {
      // 查找当前tab的数组序号
      const index = arr.indexOf(key)
      // 判断当前tab的位置
      if (index === 0) {
        // 第一位,激活后面的
        this.currentRoute.key = arr[1]
      } else {
        // 激活前面的
        this.currentRoute.key = arr[index - 1]
      }
    }
    // 删除
    this.tabs.delete(key)
  }
  // 刷新时依据url加载组件
  refresh = () => {
    const path = window.location.pathname
    if (path === '/' || path === this.baseUrl) {
      // 首页
    } else {
      const tmp = path.replace(this.baseUrl, '')
      // 验证路由
      for (const key inthis.routes) {
        const route = this.routes[key]
        if (route.path === tmp) {
          this.currentRoute.key = key
          break
        }
      }
    }
  }
}
/**
 * 创建简易路由
 */
const createRouter = (info) => {
  // 创建路由,
  const router = new Router(info)
  // 使用vue的插件,设置全局路由
  return(app) => {
    // 便于模板获取
    app.config.globalProperties.$router = router
    // 便于代码获取
    app.provide(flag, router)
  }
}
// 在代码里获取路由
const useRouter = () => {
  return inject(flag)
}
export {
  createRouter,
  useRouter
}

首先定义一个class,存放需要的各种属性和处理方法,然后做一个Vue的插件,便于做初始化的设置和全局变量。最后做一个获取路由的函数即可。

菜单组件:nf-menu

<el-menu
    ref="domMenu"
    class="el-menu-vertical-demo"
    default-active="1"
    @select="(index) => {$router.currentRoute.key = index}"
    background-color="#6c747c"
    text-color="#fff"
    active-text-color="#ffd04b"
  >
    <el-sub-menu v-for="(item, index) in $router.group"
      :key="index"
      :index="item.id"
    >
      <template #title>
        <component
          :is="item.icon"
          style="width: 1.5em; height: 1.5em; margin-right: 8px;"
        >
        </component>
        <span>{{item.title}}</span>
      </template>
      <el-menu-item v-for="(key, index) in item.children"
        :key="index"
        :index="key">
        <template #title>
          <component
            :is="$router.routes[key].icon"
            style="width: 1.5em; height: 1.5em; margin-right: 8px;"
          >
          </component>
          {{$router.routes[key].title}}
        </template>
      </el-menu-item>
    </el-sub-menu>
  </el-menu>

封装的不够细致,主要目的是可以偷懒用着方便就好。 不求灵活,只求方便,简单粗暴的实现功能即可。

单页路由视图:router-view

<template>
  <component :is="$router.getComponent()">
  </component>
</template>

这个就很简单了,用动态组件加载需要的组件即可。

动态tab标签页:router-view-tabs

<el-tabs
    v-model="$router.currentRoute.key"
    type="card"
  >
    <el-tab-pane label="桌面" :name="main">
      <component :is="$router.home">
      </component>
    </el-tab-pane>
    <el-tab-pane
      v-for="key in $router.tabs"
      :key="key"
      :label="$router.routes[key].title"
      :name="key"
    >
     <template #label>
        <span>{{$router.routes[key].title}} &nbsp;
          <circle-close-filled
            style="width: 1.0em; height: 1.0em; margin-top: 8px;"
            @click.stop="$router.removeTab(key)" />
        </span>
      </template>
      <component :is="$router.routerControl[key]">
      </component>
    </el-tab-pane>
  </el-tabs>

这个稍微复杂一点,用属性绑定 el-tabs,设置属性、图标和事件 。


在项目里的使用方法

首先定义一个路由,然后在 main.js 里面挂载。然后布局里面加载组件即可。

  • 定义路由和菜单
    /router/index.js
import { Loading, Connection, Edit, FolderOpened } from'@element-plus/icons'
import { createRouter } from'/nf-ui-core'
import home from'../views/home.vue'
exportdefault createRouter({
  /**
   * 基础路径
   */
  baseUrl: '/nf-rollup-ui-controller',
  /**
   * 首页
   */
  home: home,
  /**
   * 一级菜单,设计包含哪些二级菜单
   */
  group = [
    {
      id: 1,
      title: '基础控件',
      icon: FolderOpened,
      children: [
        'base_html',
        'base_ui',
        'base_transmit',
        'base_item'
      ]
    },
    {
      id: 2,
      title: '复合控件',
      icon: FolderOpened,
      children: [
        'nf_form',
        'nf_find',
        'nf_grid',
        'nf_button',
        'nf_crud'
      ]
    }
  ],
  /**
   * 二级菜单,设置路径、标题、图标和加载的组件
   */
  routes = {
    base_html: {
      path: '/base-html', title: '原生HTML', icon: Edit,
      component: () =>import('../views/ui/base/c-01html.vue')
    },
    base_ui: {
      path: '/base-ui', title: 'UI库组件', icon: Edit,
      component: () =>import('../views//ui/base/c-02UI.vue')
    }, 
    ... 略
  }
})
  • 在 main.js 里挂载路由和组件
import { createApp } from'vue'
import App from'./App.vue'
// 基于element-plus 二次封装的组件
import { nfElementPlus } from'/nf-ui-elp'
// 简易路由
import router from'./router'
createApp(App)
  .use(nfElementPlus) // 全局注册组件
  .use(router) // 注册路由
  .mount('#app')
  • 在App.vue 里面做页面布局
<el-container>
    <el-aside width="200px">
      <!--菜单-->
      <nf-menu/>
    </el-aside>
    <el-main>
      <el-radio-group v-model="routerKind" size="mini">
        <el-radio-button label="单页"></el-radio-button>
        <el-radio-button label="tabs"></el-radio-button>
      </el-radio-group> 可以切换单页模式、动态tab模式
      <hr>
      <!--路由视图-->
      <router-view v-if="routerKind === '单页'"></router-view>
      <router-view-tabs v-if="routerKind === 'tabs'"></router-view-tabs>
    </el-main>
  </el-container>

这里为了演示,用了两种模式,项目里选择一个喜欢的就好。

是不是很简单,把繁琐的操作都封装好,以后再用就简单多了,只需要定义路由就好。

疑问

  • 单层路由够用吗? 对于我来说够用了,如果以后发现有不够用的地方还可以继续完善,不过肯定不会完善到 VueRouter 的程度,因为那样的话,为啥不直接用 VueRouter ?
  • 太简陋了吧? 是的,比较简陋,目前只是练练手,方便实现一些小功能的演示。

本文作者:自然框架

个人网址:jyk.cnblogs.com

声明:本文为 脚本之家专栏作者 投稿,未经允许请勿转载。

相关文章
|
7月前
|
前端开发 关系型数据库 MySQL
TDesign中后台管理系统-访问后端服务
TDesign中后台管理系统-访问后端服务
|
9月前
|
缓存 JavaScript 前端开发
Vue 轻量级后台管理系统基础模板
Vue 轻量级后台管理系统基础模板
88 1
|
10月前
|
小程序 安全 数据安全/隐私保护
微信小程序项目实例——密码管理器
微信小程序项目实例——密码管理器
微信小程序项目实例——密码管理器
|
5月前
vue2实现后台管理系统的侧边栏切换子页面
vue2实现后台管理系统的侧边栏切换子页面
57 0
|
6月前
|
存储 JavaScript 数据安全/隐私保护
Vue3.0商店后台管理系统项目实战-路由守卫(登录状态储存)
Vue3.0商店后台管理系统项目实战-路由守卫(登录状态储存)
28 0
|
10月前
|
开发工具 git
vue2 实现后台管理系统左侧菜单联动实现 tab根据路由切换联动内容,并支持移动端框架
vue2 实现后台管理系统左侧菜单联动实现 tab根据路由切换联动内容,并支持移动端框架
89 0
|
10月前
|
JavaScript 开发工具 git
vue2 实现后台管理系统左侧菜单联动实现 tab根据路由切换联动内容
vue2 实现后台管理系统左侧菜单联动实现 tab根据路由切换联动内容
173 0
uniapp登陆页面功能
uniapp登陆页面功能
149 0
|
缓存 JavaScript 前端开发
手把手教你怎么实现一个后台管理系统——菜单权限篇(一)
手把手教你怎么实现一个后台管理系统——菜单权限篇(一)
手把手教你怎么实现一个后台管理系统——菜单权限篇(一)