补发团队项目开发02——前端页面实现根据路由动态生成侧边栏(改编苍穹外卖)

团队初始开发时 采用苍穹外卖模板,意外的发现其侧边栏是根据路由动态生成的,这里通过添加子路由,改变侧边栏生成逻辑进行修改。
首先我们系统有多个用户,所以不能直接再router.ts文件中直接添加路由,我们先对这边代码文件进行改编:(仅作参考)在project-sky-admin-vue-ts\src\layout\components\Sidebar\index.vue中(不过这边样式有些差别 不过影响不大)

<template>
  <div>
    <!-- Logo 区域 -->
    <div class="logo">
      <!-- 根据 isCollapse 的值动态切换 Logo 图片 -->
      <div v-if="!isCollapse" class="sidebar-logo">
        <img src="@/assets/login/device_logo.png" style="width: 150px; height: 50px">
      </div>
      <div v-else class="sidebar-logo-mini">
        <img src="@/assets/login/mini-logo.png">
      </div>
    </div>
    <!-- 滚动条包裹菜单,确保内容可滚动 -->
    <el-scrollbar wrap-class="scrollbar-wrapper">
      <!-- 菜单组件 -->
      <el-menu :default-openeds="defOpen" :default-active="defAct" :collapse="isCollapse"
        :background-color="variables.menuBg" :text-color="variables.menuText"
        :active-text-color="variables.menuActiveText" :unique-opened="false" :collapse-transition="false"
        mode="vertical">
        <!-- 动态生成菜单项 -->
        <sidebar-item v-for="route in routes" :key="route.path" :item="route" :base-path="route.path"
          :is-collapse="isCollapse" />
      </el-menu>
    </el-scrollbar>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { AppModule } from '@/store/modules/app';
import { UserModule } from '@/store/modules/user';
import SidebarItem from './SidebarItem.vue';
import variables from '@/styles/_variables.scss';
import { getSidebarStatus, setSidebarStatus } from '@/utils/cookies';
import Cookies from 'js-cookie';

@Component({
  name: 'SideBar',
  components: {
    SidebarItem
  }
})
export default class extends Vue {
  // 用户角色
  get roleId() {
    console.log("角色登录id为");
    console.log("角色登录id为" + UserModule.roleId);
    return UserModule.roleId; // 从 Vuex 的 UserModule 中获取用户角色
  }

  // 当前用户的名称
  get name() {
    return (UserModule.userInfo as any).name
      ? (UserModule.userInfo as any).name
      : JSON.parse(Cookies.get('user_info') as any).name; // 从 Vuex 或 Cookie 中获取用户名
  }

  get defOpen() {
  console.log("角色登录id为", this.roleId);
  let path = ['/']; // 默认路径
  this.routes.forEach((n: any, i: number) => {
    if (n.meta && n.meta.roleId === this.roleId) {
      path.splice(0, 1, n.path); // 根据用户角色动态设置默认展开路径
    }
  });
  console.log("默认展开路径为", path);
  return path;
}

  // 默认激活的菜单路径
  get defAct() {
    return this.$route.path; // 当前路由路径
  }

  // 获取侧边栏的状态
  get sidebar() {
    return AppModule.sidebar; // 从 Vuex 的 AppModule 中获取侧边栏状态
  }

  get routes() {
  // 获取所有路由配置
  let routes = JSON.parse(JSON.stringify([...(this.$router as any).options.routes]));
  console.log('1-=-=routes=-=-=', routes);

  // 获取当前用户的角色ID
  const currentRoleId = this.roleId;
  console.log('2-=-=currentRoleId=-=-=', currentRoleId);

  let menu: any = [];
  // 找到工区长对应的顶级路由
  if (currentRoleId === 1) {
    menu = routes.find(item => item.path === '/purchasingOffer');
  }else if (currentRoleId === 2) {
    menu = routes.find(item => item.path === '/sectionLeader');
  }else if (currentRoleId === 3) {
    menu = routes.find(item => item.path === '/teamLeader');
  }else if (currentRoleId === 4) {
    menu = routes.find(item => item.path === '/WarehouseManager');
  }else if (currentRoleId === 5) {
    menu = routes.find(item => item.path === '/director');
  }
  

  // 如果找到工区长对应的顶级路由,并且有子路由
  let menuList = [];
  if (menu && menu.children) {
    // 为每个子路由的 path 前缀加上顶级路由的路径
    menuList = menu.children.map(child => {
      return {
        ...child,
        path: `${menu.path}/${child.path}` // 动态拼接路径
      };
    });
  }

  console.log('3-=-=menuList=-=-=', menuList);
  return menuList;
}



  // 获取样式变量
  get variables() {
    return variables; // 从 SCSS 文件中导入的样式变量
  }

  // 判断侧边栏是否折叠
  get isCollapse() {
    return !this.sidebar.opened; // 根据侧边栏状态判断是否折叠
  }

  // 登出方法
  private async logout() {
    this.$store.dispatch('LogOut').then(() => { // 调用 Vuex 的 LogOut 动作
      this.$router.replace({ path: '/login' }); // 跳转到登录页面
    });
  }
}
</script>

<style lang="scss" scoped>
.logo {
  text-align: center;
  background-color: rgb(27, 31, 46);
  padding: 15px 0 0;
  height: 80px;

  img {
    display: inline-block;
  }
}

.sidebar-logo-mini {
  img {
    width: 30px;
    height: 30px;
  }
}

.el-scrollbar {
  height: 100%;
  background-color: rgb(52, 55, 68);
}

.el-menu {
  border: none;
  height: calc(95vh - 23px);
  width: 100% !important;
  padding: 47px 15px 0;
}
</style>

路由样式文件如下

import Vue from "vue";
import Router from "vue-router";
import Layout from "@/layout/Layout.vue";
import {
  getToken,
  setToken,
  removeToken,
  getStoreId,
  setStoreId,
  removeStoreId,
  setUserInfo,
  getUserInfo,
  removeUserInfo
} from "@/utils/cookies";
import store from "@/store";
import { RouterLinkStub } from "@vue/test-utils";

Vue.use(Router);

const router = new Router({
  scrollBehavior: (to, from, savedPosition) => {
    if (savedPosition) {
      return savedPosition;
    }
    return { x: 0, y: 0 };
  },
  base: process.env.BASE_URL,
  routes: [
    {
      path: "/",  
      component: () =>
        import(/* webpackChunkName: "login" */ "@/views/login/index.vue"),
      meta: { title: "设备管理系统", hidden: true, notNeedAuth: true }
    },
    {
      path: "/404",
      component: () => import(/* webpackChunkName: "404" */ "@/views/404.vue"),
      meta: { title: "设备管理系统", hidden: true, notNeedAuth: true }
    },
    //工区长
    {
      path: "/sectionLeader",
      component: Layout,
      redirect: "/sectionLeader/purchase",
      meta: { title: "工区长", icon: "purchase" },
      children: [
        {
          path: "purchase",
          component: () =>
            import(/* webpackChunkName: "shopTable" */ "@/views/sectionLeader/purchase/index.vue"),
          meta: {
            title: "设备采购管理",
            icon: "icon-order",
          }
        },

        {
          path: "purchase/add",
          component: () =>
            import(/* webpackChunkName: "shopTable" */ "@/views/sectionLeader/purchase/addPurchase.vue"),
          meta: {
            title: "添加采购任务",
            hidden: true,
          }
        },
        {
          path: "outbound",
          component: () =>
            import(/* webpackChunkName: "shopTable" */ "@/views/sectionLeader/outbound/index.vue"),
          meta: {
            title: "设备出库申请审核",
            icon: "icon-combo",
          }
        },
           {
          path: "deviceReview",
          component: () =>
            import(/* webpackChunkName: "deviceReview" */ "@/views/sectionLeader/deviceReview/index.vue"),
          redirect: "/deviceReview/faultClear",
          meta: {
            title: "设备审核",
            icon: "icon-dish",
          },
          // 添加子路由
          children: [
            {
              path: "faultClear",
              component: () =>
                import(/* webpackChunkName: "faultClear" */ "@/views/sectionLeader/deviceReview/faultClear/index.vue"),
              meta: {
                title: "故障销号",
                icon: "icon-dish",
              }
            },
            {
              path: '/sectionLeader/deviceReview/faultClear/face-recognition',
              component: () => import('@/views/sectionLeader/deviceReview/faultClear/FaceRecognition.vue'),
              name: 'FaceRecognition',
              meta: {
                title: '人脸识别验证',
                icon: 'dashboard',
                hidden: true
              },
            },
          
            
            {
              path: "inspectionAcceptance",
              component: () =>
                import(/* webpackChunkName: "inspectionAcceptance" */ "@/views/sectionLeader/deviceReview/inspectionAcceptance/index.vue"),
              meta: {
                title: "巡检验收",
                icon: "icon-dish",
              }
            },
            {
              path: "maintenanceAcceptance",
              component: () =>
                import(/* webpackChunkName: "maintenanceAcceptance" */ "@/views/sectionLeader/deviceReview/maintenanceAcceptance/index.vue"),
              meta: {
                title: "保养验收",
                icon: "icon-dish",
              }
            },
            {
              path: "testingAcceptance",
              component: () =>
                import(/* webpackChunkName: "testingAcceptance" */ "@/views/sectionLeader/deviceReview/testingAcceptance/index.vue"),
              meta: {
                title: "检测验收",
                icon: "icon-dish",
              }
            }
          ]
        },
      ]
    },
    //采购管理员
    {
      path: "/purchasingOffer",
      component: Layout,
      redirect: "/purchasingOffer/purchase",
      children: [
        {
          path: "purchase",
          component: () =>
            import(/* webpackChunkName: "shopTable" */ "@/views/purchasingOffer/purchase/index.vue"),
          meta: {
            title: "设备采购管理",
            icon: "icon-order",

          }
        },
        {
          path: "purchase/add",
          component: () =>
            import(/* webpackChunkName: "shopTable" */ "@/views/purchasingOffer/purchase/addPurchase.vue"),
          meta: {
            title: "添加采购任务",
            hidden: true,
          }
        }

      ]
    },
    //班组长
    {
      path: "/teamLeader",
      component: Layout,
      redirect: "/teamLeader/outbound",
      children: [
        {
          path: "outbound",
          component: () =>
            import(/* webpackChunkName: "shopTable" */ "@/views/teamLeader/outbound/index.vue"),
          meta: {
            title: "设备出库申请",
            icon: "icon-order",

          }
        },
        {
          path: "outbound/add",
          component: () =>
            import(/* webpackChunkName: "shopTable" */ "@/views/teamLeader/outbound/addOutbound.vue"),
          meta: {
            title: "添加采购任务",
            hidden: true,
          }
        },
        // 新增设备审核菜单
        {
          path: "deviceReview",
          component: () =>
            import(/* webpackChunkName: "deviceReview" */ "@/views/teamLeader/deviceReview/index.vue"),
          redirect: "/deviceReview/faultClear",
          meta: {
            title: "设备审核",
            icon: "icon-dish",
          },
          // 添加子路由
          children: [
            {
              path: "faultClear",
              component: () =>
                import(/* webpackChunkName: "faultClear" */ "@/views/teamLeader/deviceReview/faultClear/index.vue"),
              meta: {
                title: "故障销号",
                icon: "icon-dish",
              }
            },
            {
              path: "faultClear/add",
              component: () =>
                import(/* webpackChunkName: "faultClear" */ "@/views/teamLeader/deviceReview/faultClear/addTask.vue"),
              meta: {
                title: "添加故障报修",
                hidden: true,
              }
            },
            {
              path: '/teamLeader/deviceReview/faultClear/face-recognition',
              component: () => import('@/views/teamLeader/deviceReview/faultClear/FaceRecognition.vue'),
              name: 'FaceRecognition',
              meta: {
                title: '人脸识别验证',
                icon: 'dashboard',
                hidden: true
              },
            },            
            
            {
              path: "inspectionAcceptance",
              component: () =>
                import(/* webpackChunkName: "inspectionAcceptance" */ "@/views/teamLeader/deviceReview/inspectionAcceptance/index.vue"),
              meta: {
                title: "巡检验收",
                icon: "icon-dish",
              }
            },
            {
              path: "inspectionAcceptance/add",
              component: () =>
                import(/* webpackChunkName: "inspectionAcceptance" */ "@/views/teamLeader/deviceReview/inspectionAcceptance/addTask.vue"),
              meta: {
                title: "规划巡检计划",
                icon: "icon-dish",
                hidden: true,
              }
            },            
            {
              path: "maintenanceAcceptance",
              component: () =>
                import(/* webpackChunkName: "maintenanceAcceptance" */ "@/views/teamLeader/deviceReview/maintenanceAcceptance/index.vue"),
              meta: {
                title: "保养验收",
                icon: "icon-dish",
              }
            },
            {
              path: "maintenanceAcceptance/add",
              component: () =>
                import(/* webpackChunkName: "inspectionAcceptance" */ "@/views/teamLeader/deviceReview/maintenanceAcceptance/addTask.vue"),
              meta: {
                title: "保养验收计划",
                icon: "icon-dish",
                hidden: true,
              }
            },            
            {
              path: "testingAcceptance",
              component: () =>
                import(/* webpackChunkName: "testingAcceptance" */ "@/views/teamLeader/deviceReview/testingAcceptance/index.vue"),
              meta: {
                title: "检测验收",
                icon: "icon-dish",
              }
            },
            {
              path: "testingAcceptance/add",
              component: () =>
                import(/* webpackChunkName: "inspectionAcceptance" */ "@/views/teamLeader/deviceReview/testingAcceptance/addTask.vue"),
              meta: {
                title: "检测验收计划",
                icon: "icon-dish",
                hidden: true,
              }
            },            
          ]
        },
      ]
    },

    //仓库管理员
    //仓库管理员
    {
      path: "/WarehouseManager",
      component: Layout,
      redirect: "/WarehouseManager/dashboard",
      children: [
        {
          path: "dashboard",
          component: () =>
            import(/* webpackChunkName: "dashboard" */ "@/views/WarehouseManager/dashboard/index.vue"),
          name: "dashboard",
          meta: {
            title: "工作台",
            icon: "dashboard",
            affix: true,
          }
        },
        {
          path: "outbound",
          component: () =>
            import(/* webpackChunkName: "shopTable" */ "@/views/WarehouseManager/inbound.vue"),
          meta: {
            title: "设备入库管理",
            icon: "icon-order",

          }
        },
        {
          path: "inbound",
          component: () =>
            import(/* webpackChunkName: "shopTable" */ "@/views/WarehouseManager/outbound.vue"),
          meta: {
            title: "设备出库管理",
            icon: "icon-order",

          }
        },

        {
          path: "deviceBrowse",
          component: () =>
            import(/* webpackChunkName: "shopTable" */ "@/views/WarehouseManager/deviceBrowse.vue"),
          meta: {
            title: "仓库设备浏览",
            icon: "icon-order",

          }
        },

      ]
    },
     //信息化主任
    {
      path: "/director",
      component: Layout,
      redirect: "/director/dashboard",
      children: [
        {
          path: "dashboard",
          component: () =>
            import(/* webpackChunkName: "dashboard" */ "@/views/director/dashboard/index.vue"),
          name: "director",
          meta: {
            title: "工作台",
            icon: "dashboard",
            affix: true,

          }
        },
        // {
        //   path: "statistics",
        //   component: () =>
        //     import(/* webpackChunkName: "shopTable" */ "@/views/director/statistics/index.vue"),
        //   meta: {
        //     title: "数据统计",
        //     icon: "icon-statistics",

        //   }
        // },
        {
          path: "deviceReview",
          component: () =>
            import(/* webpackChunkName: "deviceReview" */ "@/views/director/deviceReview/index.vue"),
          redirect: "/deviceReview/faultClear",
          meta: {
            title: "任务审核管理",
            icon: "icon-dish",
          },
          // 添加子路由
          children: [
            {
              path: "faultClear",
              component: () =>
                import(/* webpackChunkName: "faultClear" */ "@/views/director/deviceReview/faultClear/faultClear.vue"),
              meta: {
                title: "故障销号",
                icon: "icon-dish",
              }
            },
            
            {
              path: "inspectionAcceptance",
              component: () =>
                import(/* webpackChunkName: "inspectionAcceptance" */ "@/views/director/deviceReview/inspectionAcceptance/inspectionAcceptance.vue"),
              meta: {
                title: "巡检验收",
                icon: "icon-dish",
              }
            },
            {
              path: "maintenanceAcceptance",
              component: () =>
                import(/* webpackChunkName: "maintenanceAcceptance" */ "@/views/director/deviceReview/maintenanceAcceptance/maintenanceAcceptance.vue"),
              meta: {
                title: "保养验收",
                icon: "icon-dish",
              }
            },
            {
              path: "testingAcceptance",
              component: () =>
                import(/* webpackChunkName: "testingAcceptance" */ "@/views/director/deviceReview/testingAcceptance/testingAcceptance.vue"),
              meta: {
                title: "检测验收",
                icon: "icon-dish",
              }
            }
          ]
        },

        {
          path: "employee",
          component: () =>
            import(/* webpackChunkName: "dashboard" */ "@/views/director/employee/index.vue"),
          meta: {
            title: "员工管理",
            icon: "dashboard",
            affix: true,

          }
        },
        {
          path: "employee/add",
          component: () =>
            import(/* webpackChunkName: "shopTable" */ "@/views/director/employee/addEmployee.vue"),
          meta: {
            title: "新增员工",
            hidden: true,
          }
        },
        {
          path: "device",
          component: () =>
            import(/* webpackChunkName: "dashboard" */ "@/views/director/device/deviceInfo.vue"),
          meta: {
            title: "设备管理",
            icon: "dashboard",
            affix: true,

          }
        },
        {
          path: "device/record",
          component: () =>
            import(/* webpackChunkName: "shopTable" */ "@/views/director/device/deviceRecord.vue"),
          meta: {
            title: "设备履历记录",
            hidden: true,
          }
        }

      ]
    },


    {
      path: "*",
      redirect: "/404",
      meta: { hidden: true }
    }
  ]
});

export default router;

同时由于不同用户登录 需要存入token 和roleId
要对文件src\store\modules\user.ts进行修改 代码如下

import { VuexModule, Module, Action, Mutation, getModule } from 'vuex-module-decorators'
import { login,userLogout } from '@/api/employee'
import { getToken, setToken, removeToken,getStoreId, setStoreId, removeStoreId, setUserInfo, getUserInfo, removeUserInfo } from '@/utils/cookies'
import store from '@/store'
import Cookies from 'js-cookie'
import { Message } from 'element-ui'
export interface IUserState {
  token: string
  name: string
  avatar: string
  storeId: string
  introduction: string
  userInfo: any
  roleId: number; // 使用单个数字存储角色ID
  username: string
}

@Module({ 'dynamic': true, store, 'name': 'user' })
class User extends VuexModule implements IUserState {
  public token = getToken() || ''
  public name = ''
  public avatar = ''
  // @ts-ignore
  public storeId: string = getStoreId() || ''
  public introduction = ''
  public userInfo = {}
  public roles: string[] = []
  public username = Cookies.get('username') || ''
  public roleId = parseInt(localStorage.getItem('roleId') || '0'); // 从 localStorage 中读取

  @Mutation
  private SET_TOKEN(token: string) {
    this.token = token
  }

  @Mutation
  private SET_NAME(name: string) {
    this.name = name
  }

  @Mutation
  private SET_USERINFO(userInfo: any) {
    this.userInfo = { ...userInfo }
  }

  @Mutation
  private SET_AVATAR(avatar: string) {
    this.avatar = avatar
  }

  @Mutation
  private SET_INTRODUCTION(introduction: string) {
    this.introduction = introduction
  }

  @Mutation
  private SET_ROLES(roles: string[]) {
    this.roles = roles
  }

  @Mutation
  private SET_STOREID(storeId: string) {
    this.storeId = storeId
  }
  @Mutation
  private SET_USERNAME(name: string) {
    this.username = name
    }
    
  @Mutation
  private SET_ROLEID(roleId: number) {
    this.roleId = roleId
    localStorage.setItem('roleId', roleId.toString()); // 将 roleId 存储到 localStorage
}

  @Action
  public async Login(userInfo: { username: string, password: string }) {
    let { username, password } = userInfo
    username = username.trim()
    this.SET_USERNAME(username)
    Cookies.set('username', username)
    const { data } = await login({ username, password })
    if (String(data.code) === '1') {
      // const dataParams = {
      //   // status: 200,
      //   token: data.data.token,
      //   // msg: '登录成功',
      //   // ...data.data
      //   ...data
      // }
      this.SET_TOKEN(data.data.token)
      setToken(data.data.token)
      this.SET_USERINFO(data.data)
      this.SET_ROLEID(data.data.roleId)
      Cookies.set('user_info', data.data)
      return data
    } else {
      return Message.error(data.msg)
    }
  }

  @Action
  public ResetToken () {
    removeToken()
    this.SET_TOKEN('')
    this.SET_ROLES([])
    this.SET_ROLEID(0); // 重置角色ID
    localStorage.removeItem('roleId'); // 从 localStorage 中移除 roleId
  }

  @Action
  public async changeStore(data: any) {
    this.SET_STOREID = data.data
    this.SET_TOKEN(data.authorization)
    setStoreId(data.data)
    setToken(data.authorization)
  }

  @Action
  public async GetUserInfo () {
    if (this.token === '') {
      throw Error('GetUserInfo: token is undefined!')
    }

    const data = JSON.parse(<string>getUserInfo()) //  { roles: ['admin'], name: 'zhangsan', avatar: '/login', introduction: '' }
    if (!data) {
      throw Error('Verification failed, please Login again.')
    }

    const { roles, name, roleId,avatar, introduction, applicant, storeManagerName, storeId='' } = data // data.user
    // roles must be a non-empty array
/*     if (!roles || roles.length <= 0) {
      throw Error('GetUserInfo: roles must be a non-null array!')
    } */

    this.SET_ROLES(roles)
    this.SET_USERINFO(data)
    this.SET_NAME(name || applicant || storeManagerName)
    this.SET_AVATAR(avatar)
    this.SET_ROLEID(roleId)
    this.SET_INTRODUCTION(introduction)
  }

  @Action
  public async LogOut () {
    const { data } = await userLogout({})
    removeToken()
    this.SET_TOKEN('')
    this.SET_ROLES([])
    Cookies.remove('username')
    Cookies.remove('user_info')
    localStorage.removeItem('roleId'); // 从 localStorage 中移除 roleId
    this.SET_ROLEID(0); // 重置角色ID
    removeUserInfo()
  }
}

export const UserModule = getModule(User)

同时不同用户登录跳转src\views\login\index.vue

<template>
  <div class="login">
    <div class="login-box">
      <img src="@/assets/login/1.png" alt="" />
      <div class="login-form">
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules">
          <div class="login-form-title">
            <img
              src="@/assets/login/icon_logo.png"
              style="width: 149px; height: 38px"
              alt=""
            />
            <!-- <span class="title-label">苍穹外卖</span> -->
          </div>
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              type="text"
              auto-complete="off"
              placeholder="账号"
              prefix-icon="iconfont icon-user"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="密码"
              prefix-icon="iconfont icon-lock"
              @keyup.enter.native="handleLogin"
            />
          </el-form-item>
          <el-form-item style="width: 100%">
            <el-button
              :loading="loading"
              class="login-btn"
              size="medium"
              type="primary"
              style="width: 100%"
              @click.native.prevent="handleLogin"
            >
              <span v-if="!loading">登录</span>
              <span v-else>登录中...</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import { Route } from 'vue-router'
import { Form as ElForm, Input } from 'element-ui'
import { UserModule } from '@/store/modules/user'
import { isValidUsername } from '@/utils/validate'

@Component({
  name: 'Login',
})
export default class extends Vue {
  private validateUsername = (rule: any, value: string, callback: Function) => {
    if (!value) {
      callback(new Error('请输入用户名'))
    } else {
      callback()
    }
  }
  private validatePassword = (rule: any, value: string, callback: Function) => {
    if (value.length < 6) {
      callback(new Error('密码必须在6位以上'))
    } else {
      callback()
    }
  }
  private loginForm = {
    username: 'admin',
    password: '123456',
  } as {
    username: String
    password: String
  }

  loginRules = {
    username: [{ validator: this.validateUsername, trigger: 'blur' }],
    password: [{ validator: this.validatePassword, trigger: 'blur' }],
  }
  private loading = false
  private redirect?: string

  @Watch('$route', { immediate: true })
  private onRouteChange(route: Route) {}

  // 登录
  private handleLogin() {
    ;(this.$refs.loginForm as ElForm).validate(async (valid: boolean) => {
      if (valid) {
        this.loading = true
        //this.$message.info('正在登录,请稍候...')  // 添加这一行
        await UserModule.Login(this.loginForm as any)
          .then((res: any) => {
            if (String(res.code) === '1') {
       
              if (res.data.roleId === 1) {
                this.$router.push('/purchasingOffer')
              } else if (res.data.roleId === 2) {
                this.$router.push('/sectionLeader')
              }else if (res.data.roleId === 3) {
                this.$router.push('/teamLeader')
              }else if (res.data.roleId === 4) {
                this.$router.push('/WarehouseManager')
              }else if (res.data.roleId === 5) {
                this.$router.push('/director')
              }
            } else {
              // this.$message.error(res.msg)
              this.loading = false
            }
          })
          .catch(() => {
            // this.$message.error('用户名或密码错误!')
            this.loading = false
          })
      } else {
        return false
      }
    })
  }
}
</script>

<style lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  // background: #476dbe;
  background-color: #333;
}

.login-box {
  width: 1000px;
  height: 474.38px;
  border-radius: 8px;
  display: flex;
  img {
    width: 60%;
    height: auto;
  }
}

.title {
  margin: 0px auto 10px auto;
  text-align: left;
  color: #707070;
}

.login-form {
  background: #ffffff;
  width: 40%;
  border-radius: 0px 8px 8px 0px;
  display: flex;
  justify-content: center;
  align-items: center;
  .el-form {
    width: 214px;
    height: 307px;
  }
  .el-form-item {
    margin-bottom: 30px;
  }
  .el-form-item.is-error .el-input__inner {
    border: 0 !important;
    border-bottom: 1px solid #fd7065 !important;
    background: #fff !important;
  }
  .input-icon {
    height: 32px;
    width: 18px;
    margin-left: -2px;
  }
  .el-input__inner {
    border: 0;
    border-bottom: 1px solid #e9e9e8;
    border-radius: 0;
    font-size: 12px;
    font-weight: 400;
    color: #333333;
    height: 32px;
    line-height: 32px;
  }
  .el-input__prefix {
    left: 0;
  }
  .el-input--prefix .el-input__inner {
    padding-left: 26px;
  }
  .el-input__inner::placeholder {
    color: #aeb5c4;
  }
  .el-form-item--medium .el-form-item__content {
    line-height: 32px;
  }
  .el-input--medium .el-input__icon {
    line-height: 32px;
  }
}

.login-btn {
  border-radius: 17px;
  padding: 11px 20px !important;
  margin-top: 10px;
  font-weight: 500;
  font-size: 12px;
  border: 0;
  font-weight: 500;
  color: #333333;
  // background: #09a57a;
  background-color: hwb(215 27% 7% / 0.909);
  &:hover,
  &:focus {
    // background: #09a57a;
    background-color: #1606f1;
    color: #ffffff;
  }
}
.login-form-title {
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 40px;
  .title-label {
    font-weight: 500;
    font-size: 20px;
    color: #333333;
    margin-left: 10px;
  }
}
</style>

以上是针对苍穹外卖前端侧边栏和实现不同登录用户修改 修改完成,查阅了很多资料发现找不到,只能自己修改了。不过到最后发现其实框架使用的不算多,还是自己编写快一些,不过苍穹外卖项目样式确实好

posted @ 2025-06-08 15:24  好像是Cwk  阅读(22)  评论(0)    收藏  举报