zhangwei
2025-08-22 85c54d88f139096614aea4b06f2166cae27729d7
src/views/login/index.vue
@@ -1,4 +1,4 @@
<script setup lang="ts">
<script setup lang="tsx">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
@@ -7,15 +7,26 @@
  reactive,
  computed,
  ref,
  Ref,
  h,
  onMounted,
  defineAsyncComponent,
  onUnmounted,
  watch
} from "vue";
import { debounce } from "@pureadmin/utils";
import { debounce, storageLocal } from "@pureadmin/utils";
import { useNav } from "@/layout/hooks/useNav";
import { useEventListener } from "@vueuse/core";
import type { FormInstance } from "element-plus";
import {
  ElForm,
  ElFormItem,
  ElRadioGroup,
  ElRadio,
  ElRow,
  ElTag,
  ElCol
} from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
@@ -25,12 +36,7 @@
import { useRoute } from "vue-router";
const route = useRoute();
// import dayIcon from "@/assets/svg/day.svg?component";
// import darkIcon from "@/assets/svg/dark.svg?component";
import Lock from "~icons/ri/lock-fill";
import User from "~icons/ri/user-3-fill";
import { captcha, phoneNumberCode, exRole } from "@/api/register/index.ts";
import { captcha, phoneNumberCode, exRole } from "@/api/register/index";
defineOptions({
  name: "Login"
@@ -50,15 +56,18 @@
// 获取验证码
const getCaptcha = async () => {
  // if (!state.captchaEnabled) return;
  state.ruleForm.code = "";
  const res = await captcha();
  console.log(res);
  state.captchaImage = "data:text/html;base64," + res.result?.img;
  state.expirySeconds = res.result?.expirySeconds;
  state.ruleForm.codeId = res.result?.id;
};
import {
  addDialog,
  closeDialog,
  updateDialog,
  closeAllDialog
} from "@/components/ReDialog";
const state = reactive({
  isShowPassword: false,
  ruleForm: {
@@ -66,9 +75,8 @@
    nickName: "",
    phone: "",
    phoneVCode: "",
    // tenantId: props.tenantInfo.id,
    code: "",
    codeId: 0,
    codeId: "",
    email: "",
    exRoleCode: ""
  },
@@ -110,42 +118,23 @@
  hideTenantForLogin: false,
  expirySeconds: 60, // 验证码过期时间
  phoneSeconds: 0, // 手机验证码倒计时
  roleList: []
  roleList: [],
  myEnterpriseList: [],
  nowRole: {}
});
let secondCode = "";
let secondId: Ref<string | number | boolean> = ref("");
// 验证码过期计时器
let timer: any = null;
let phonetimer: any = null;
// 页面初始化
onMounted(async () => {
  // 若URL带有Token参数(第三方登录)
  const accessToken = route.query.token;
  // if (accessToken) await saveTokenAndInitRoutes(accessToken);
  // watch(
  //   () => themeConfig.value.isLoaded,
  //   isLoaded => {
  //     if (isLoaded) {
  // 获取登录配置
  // state.hideTenantForLogin = themeConfig.value.hideTenantForLogin ?? true;
  // state.secondVerEnabled = themeConfig.value.secondVer ?? true;
  // state.captchaEnabled = themeConfig.value.captcha ?? true;
  // 获取验证码
  getCaptcha();
  exRole().then(res => {
    state.roleList = res.result;
  });
  // 注册验证码过期计时器
  // if (state.captchaEnabled) {
  timer = setInterval(() => {
    if (state.expirySeconds > 0) state.expirySeconds -= 1;
  }, 1000);
  // }
  // }
  // },
  // { immediate: true }
  // );
});
// 页面卸载
onUnmounted(() => {
@@ -155,37 +144,170 @@
  clearInterval(phonetimer);
  phonetimer = null;
});
const openDialog = () => {
  addDialog({
    width: "30%",
    title: "选择登录公司",
    contentRenderer: () =>
      h(
        ElForm,
        {
          ref: ruleFormRef,
          model: state.ruleForm,
          rules: loginRules,
          size: "large"
        },
        {
          default: () => {
            return [
              h(
                ElFormItem,
                { prop: "exRoleCode", label: "" },
                {
                  default: () => {
                    return [
                      h(
                        ElRadioGroup,
                        {
                          modelValue: secondId.value,
                          "onUpdate:modelValue": val => (secondId.value = val)
                        },
                        // ElRadioGroup 的内容是循环生成的,用函数包裹
                        () =>
                          state.myEnterpriseList.map(item =>
                            h(
                              ElRow,
                              { style: { width: "100%" } },
                              {
                                default: () => {
                                  return [
                                    h(
                                      ElCol,
                                      { span: 24 },
                                      {
                                        default: () => {
                                          return [
                                            h(
                                              ElRadio,
                                              {
                                                key: item.customerUserID,
                                                value: item.customerUserID
                                              },
                                              // ElRadio 的内容是动态的,用函数包裹
                                              () => [
                                                // 文本直接返回(不要嵌套函数)
                                                item.enterpriseName,
                                                item.isManger
                                                  ? h(
                                                      ElTag,
                                                      {
                                                        type: "primary",
                                                        size: "small",
                                                        style: {
                                                          marginLeft: "8px",
                                                          alignSelf: "center"
                                                        }
                                                      },
                                                      // ElTag 的内容是静态文本,直接返回
                                                      {
                                                        default: () => "管理员"
                                                      }
                                                    )
                                                  : null
                                              ]
                                            )
                                          ];
                                        }
                                      }
                                    )
                                  ];
                                }
                              }
                            )
                          )
                      )
                    ];
                  }
                }
              )
            ];
          }
        }
      ),
    // jsx 语法 (注意在.vue文件启用jsx语法,需要在script开启lang="tsx")
    closeCallBack: ({ options, args }) => {
      if (args?.command === "cancel") {
        // 您点击了取消按钮
      } else if (args?.command === "sure") {
        let obj = {
          phone: state.ruleForm.phone,
          code: secondCode,
          id: secondId.value
        };
        useUserStoreHook()
          .loginByUsername(obj)
          .then(res => {
            if (res?.code == 200) {
              message("登录成功!", { type: "success" });
              router.replace({
                path: "/Index"
              });
            } else {
              message(res?.message, { type: "warning" });
            }
          });
      } else {
      }
    }
  });
};
// 点击登录
const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(valid => {
    if (valid) {
      let obj = {
        phone: state.ruleForm.phone,
        code: state.ruleForm.phoneVCode,
        exRuleCode: state.ruleForm.exRoleCode
      };
      loading.value = true;
      useUserStoreHook()
        .loginByUsername({
          phone: state.ruleForm.phone,
          code: state.ruleForm.phoneVCode,
          exRuleCode: state.ruleForm.exRoleCode
        })
        .loginByUsername(obj)
        .then(res => {
          if (res.code == 200) {
            // 获取后端路由
            return initRouter().then(() => {
              disabled.value = true;
              router
                .push(getTopMenu(true)?.path)
                .then(() => {
                  message("登录成功", { type: "success" });
                })
                .finally(() => (disabled.value = false));
              let obj = res.result;
              if (obj.theLastLogo) {
                router
                  .replace({
                    path: "/Index"
                  })
                  .then(() => {
                    message("登录成功", { type: "success" });
                  })
                  .finally(() => (disabled.value = false));
              } else {
                state.myEnterpriseList = obj.customerExs;
                secondCode = obj.code;
                openDialog();
              }
            });
          } else {
            message(res?.message || "登录失败", { type: "error" });
          }
        })
        .finally(() => (loading.value = false));
        .finally(() => {
          loading.value = false;
          disabled.value = false;
        });
    }
  });
};
// 发送手机验证码
const sendValidationCode = async () => {
  if (!state.ruleForm.phone) {
    return message("请先输入手机号", { type: "warning" });
@@ -223,26 +345,12 @@
    <div class="wave">
      <img width="400px" :src="logo1" class="logo1" />
    </div>
    <!-- <img :src="bg" class="wave" /> -->
    <div class="flex-c absolute right-5 top-3">
      <!-- 主题 -->
      <el-switch
        v-model="dataTheme"
        inline-prompt
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        @change="dataThemeChange"
      />
    </div>
    <div class="login-container">
      <div class="img">
        <!-- <component :is="toRaw(illustration)" /> -->
      </div>
      <div class="img" />
      <div class="login-box">
        <div class="login-form">
          <!-- <avatar class="avatar" /> -->
          <Motion>
            <h2 class="outline-hidden">{{ title }}</h2>
            <h2 class="logintitle">登录</h2>
          </Motion>
          <el-form
@@ -251,18 +359,6 @@
            :rules="loginRules"
            size="large"
          >
            <Motion :delay="150">
              <el-form-item prop="exRoleCode">
                <el-radio-group v-model="state.ruleForm.exRoleCode">
                  <el-radio
                    v-for="item in state.roleList"
                    :key="item.id"
                    :value="item.code"
                    >{{ item.name }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </Motion>
            <Motion :delay="100">
              <el-form-item
                :rules="[
@@ -315,16 +411,6 @@
                  </div>
                </el-col>
              </el-form-item>
              <!-- <el-form-item prop="password">
                <el-input
                  v-model="ruleForm.password"
                  clearable
                  show-password
                  placeholder="密码"
                  :prefix-icon="useRenderIcon(Lock)"
                />
              </el-form-item> -->
            </Motion>
            <Motion :delay="150">
              <el-form-item prop="phoneVCode">
@@ -338,7 +424,7 @@
                      <span
                        id="suffix-span-2"
                        ref="spanRef"
                        @click="sendValidationCode(state.ruleForm.phone)"
                        @click="sendValidationCode"
                      >
                        获取验证码
                      </span>
@@ -382,4 +468,44 @@
#suffix-span {
  cursor: pointer;
}
.login-content-code {
  display: flex;
  align-items: center;
  justify-content: space-around;
  position: relative;
  .login-content-code-img {
    width: 100%;
    height: 40px;
    line-height: 40px;
    background-color: #ffffff;
    // /* border: 1px solid rgb(220, 223, 230); */
    cursor: pointer;
    transition: all ease 0.2s;
    border-radius: 4px;
    user-select: none;
    &:hover {
      border-color: #c0c4cc;
      transition: all ease 0.2s;
    }
  }
}
.login-content-code-expired {
  @extend .login-content-code;
  &::before {
    content: "验证码已过期";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    border-radius: 4px;
    background-color: rgba(0, 0, 0, 0.5);
    color: #ffffff;
    text-align: center;
    line-height: 40px;
  }
}
</style>