commit code.

main
ZhouXY108 2022-12-30 01:56:26 +08:00
parent d81542921b
commit 7841e706f6
26 changed files with 378 additions and 273 deletions

1
.env 100644
View File

@ -0,0 +1 @@
VITE_TOKEN_NAME=plusone

1
.env.development 100644
View File

@ -0,0 +1 @@
VITE_BASE_API=http://localhost:8108

1
.env.prod 100644
View File

@ -0,0 +1 @@
VITE_BASE_API=http://api.plusone.zhouxy.xyz:8108

View File

@ -1,18 +1,18 @@
/* eslint-env node */ /* eslint-env node */
require('@rushstack/eslint-patch/modern-module-resolution') require("@rushstack/eslint-patch/modern-module-resolution");
module.exports = { module.exports = {
root: true, root: true,
extends: [ extends: [
'plugin:vue/vue3-essential', "plugin:vue/vue3-essential",
'eslint:recommended', "eslint:recommended",
'@vue/eslint-config-typescript', "@vue/eslint-config-typescript",
'@vue/eslint-config-prettier', "@vue/eslint-config-prettier",
], ],
parserOptions: { parserOptions: {
ecmaVersion: 'latest', ecmaVersion: "latest",
}, },
rules: { rules: {
'vue/multi-word-component-names': 'off', "vue/multi-word-component-names": "off",
}, },
} };

View File

@ -1,8 +1,8 @@
{ {
"singleQuote": true, "singleQuote": false,
"semi": false, "semi": true,
"useTabs": false, "useTabs": false,
"tabWidth": 4, "tabWidth": 4,
"printWidth": 110, "printWidth": 110,
"endOfLine": "lf" "endOfLine": "lf"
} }

7
env.d.ts vendored
View File

@ -1 +1,8 @@
/// <reference types="vite/client" /> /// <reference types="vite/client" />
declare interface Window {
$message: any;
$notification: any;
$dialog: any;
$loadingBar: any;
}

View File

@ -1,23 +1,21 @@
<template> <template>
<n-config-provider :theme-overrides="themeOverrides"> <n-config-provider :theme-overrides="themeOverrides">
<n-message-provider> <router-view />
<router-view />
</n-message-provider>
</n-config-provider> </n-config-provider>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { NConfigProvider, type GlobalThemeOverrides } from 'naive-ui' import { NConfigProvider, type GlobalThemeOverrides } from "naive-ui";
const themeOverrides: GlobalThemeOverrides = { const themeOverrides: GlobalThemeOverrides = {
common: { common: {
primaryColor: '#6777ef', primaryColor: "#6777ef",
primaryColorHover: 'rgba(103, 119, 239, 0.8)', primaryColorHover: "rgba(103, 119, 239, 0.8)",
primaryColorPressed: '#515dbc', primaryColorPressed: "#515dbc",
borderRadius: '4px', borderRadius: "4px",
}, },
Button: { Button: {
fontSizeLarge: '18px', fontSizeLarge: "18px",
}, },
// Select: { // Select: {
// peers: { // peers: {
@ -26,5 +24,5 @@ const themeOverrides: GlobalThemeOverrides = {
// }, // },
// }, // },
// }, // },
} };
</script> </script>

10
src/api/account.ts 100644
View File

@ -0,0 +1,10 @@
import type { LoginByPasswordCommand } from "@/type/commands/LoginCommands";
import http from "@/utils/request";
export function loginByPassword(loginByPasswordCommand: LoginByPasswordCommand) {
return http({
url: "/login/byPassword",
method: "post",
data: loginByPasswordCommand,
});
}

View File

@ -3,7 +3,7 @@
<n-layout-header position="absolute" :inverted="dark" :style="invertedStyle" :bordered="!dark"> <n-layout-header position="absolute" :inverted="dark" :style="invertedStyle" :bordered="!dark">
<Logo :collapsed="false" style="width: 224px" /> <Logo :collapsed="false" style="width: 224px" />
<div class="header"> <div class="header">
<n-button type="primary" @click="dark = !dark">{{ dark ? '亮色' : '暗色' }}</n-button> <n-button type="primary" @click="dark = !dark">{{ dark ? "亮色" : "暗色" }}</n-button>
颐和园路 颐和园路
</div> </div>
</n-layout-header> </n-layout-header>
@ -36,31 +36,31 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { defineComponent, ref, computed } from 'vue' import { defineComponent, ref, computed } from "vue";
import Logo from './components/Logo.vue' import Logo from "./components/Logo.vue";
import SiderMenu from './components/SiderMenu.vue' import SiderMenu from "./components/SiderMenu.vue";
export default defineComponent({ export default defineComponent({
name: 'MainPage', name: "MainPage",
components: { components: {
Logo, Logo,
SiderMenu, SiderMenu,
}, },
setup() { setup() {
const collapsed = ref(false) const collapsed = ref(false);
const dark = ref(true) const dark = ref(true);
const invertedStyle = computed(() => { const invertedStyle = computed(() => {
return dark.value ? { '--n-color': '#282c34' } : { '--n-color': '#ffffff' } return dark.value ? { "--n-color": "#282c34" } : { "--n-color": "#ffffff" };
}) });
return { return {
activeKey: ref<string | null>(null), activeKey: ref<string | null>(null),
collapsed, collapsed,
dark, dark,
invertedStyle, invertedStyle,
} };
}, },
}) });
</script> </script>
<style scoped> <style scoped>

View File

@ -6,16 +6,16 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { computed } from 'vue' import { computed } from "vue";
const props = defineProps({ const props = defineProps({
collapsed: Boolean, collapsed: Boolean,
inverted: Boolean, inverted: Boolean,
}) });
const style = computed(() => { const style = computed(() => {
return props.inverted ? { color: '#ffffff' } : { color: 'unset' } return props.inverted ? { color: "#ffffff" } : { color: "unset" };
}) });
</script> </script>
<style scoped> <style scoped>

View File

@ -1,39 +1,39 @@
import type { MenuOption } from 'naive-ui' import type { MenuOption } from "naive-ui";
import { type RouteRecordRaw, RouterLink } from 'vue-router' import { type RouteRecordRaw, RouterLink } from "vue-router";
import { NIcon } from 'naive-ui' import { NIcon } from "naive-ui";
import * as iconComponents from '@vicons/fluent' import * as iconComponents from "@vicons/fluent";
import { type Component, h } from 'vue' import { type Component, h } from "vue";
export interface MenuVO { export interface MenuVO {
type: number type: number;
typeName: string typeName: string;
id: number id: number;
parentId: number parentId: number;
name: string name: string;
// 若 type 为 MENU_ITEM 且 path 以 http:// 或 https:// 开头则被识别为外链 // 若 type 为 MENU_ITEM 且 path 以 http:// 或 https:// 开头则被识别为外链
path: string path: string;
title: string title: string;
icon: string icon: string;
hidden: boolean hidden: boolean;
orderNumber: number orderNumber: number;
status: number status: number;
remarks: string remarks: string;
// MENU_ITEM // MENU_ITEM
component?: string component?: string;
cache?: boolean cache?: boolean;
resource?: string resource?: string;
actions?: ActionVO[] actions?: ActionVO[];
// MENU_LIST // MENU_LIST
children?: MenuVO[] children?: MenuVO[];
} }
interface ActionVO { interface ActionVO {
id: number id: number;
identifier: string identifier: string;
label: string label: string;
value: string value: string;
} }
export enum MenuType { export enum MenuType {
@ -48,7 +48,7 @@ export function convertToRoutes(menuVOTree: MenuVO[]): RouteRecordRaw[] {
path: menuVO.path, path: menuVO.path,
name: menuVO.name, name: menuVO.name,
component: component:
menuVO.component !== undefined ? () => import('@/views' + menuVO.component) : undefined, menuVO.component !== undefined ? () => import("@/views" + menuVO.component) : undefined,
children: convertToRoutes(menuVO.children ? menuVO.children : []), children: convertToRoutes(menuVO.children ? menuVO.children : []),
meta: { meta: {
title: menuVO.title, title: menuVO.title,
@ -58,12 +58,12 @@ export function convertToRoutes(menuVOTree: MenuVO[]): RouteRecordRaw[] {
status: menuVO.status, status: menuVO.status,
remarks: menuVO.remarks, remarks: menuVO.remarks,
}, },
} };
} else { } else {
return { return {
path: menuVO.path, path: menuVO.path,
name: menuVO.name, name: menuVO.name,
component: import('@/views' + menuVO.component), component: import("@/views" + menuVO.component),
meta: { meta: {
title: menuVO.title, title: menuVO.title,
icon: menuVO.icon, icon: menuVO.icon,
@ -72,11 +72,11 @@ export function convertToRoutes(menuVOTree: MenuVO[]): RouteRecordRaw[] {
status: menuVO.status, status: menuVO.status,
remarks: menuVO.remarks, remarks: menuVO.remarks,
}, },
} };
} }
}) });
return routes return routes;
} }
export function convertToMenuOptions(menuVOTree: MenuVO[]): MenuOption[] { export function convertToMenuOptions(menuVOTree: MenuVO[]): MenuOption[] {
@ -86,28 +86,28 @@ export function convertToMenuOptions(menuVOTree: MenuVO[]): MenuOption[] {
key: menuVO.name, key: menuVO.name,
icon: renderIcon(menuVO.icon), icon: renderIcon(menuVO.icon),
label: label:
menuVO.path.startsWith('http://') || menuVO.path.startsWith('https://') menuVO.path.startsWith("http://") || menuVO.path.startsWith("https://")
? () => h('a', { href: menuVO.path, target: '_blank' }, menuVO.title) ? () => h("a", { href: menuVO.path, target: "_blank" }, menuVO.title)
: () => h(RouterLink, { to: menuVO.path }, menuVO.title), : () => h(RouterLink, { to: menuVO.path }, menuVO.title),
} };
} else { } else {
return { return {
key: menuVO.name, key: menuVO.name,
icon: renderIcon(menuVO.icon), icon: renderIcon(menuVO.icon),
label: menuVO.title, label: menuVO.title,
children: convertToMenuOptions(menuVO.children ? menuVO.children : []), children: convertToMenuOptions(menuVO.children ? menuVO.children : []),
} };
} }
}) });
return menuOptions return menuOptions;
} }
const icons: Map<string, Component> = new Map(Object.entries(iconComponents)) const icons: Map<string, Component> = new Map(Object.entries(iconComponents));
export function renderIcon(icon: string) { export function renderIcon(icon: string) {
const iconComponent = icons.get(icon) const iconComponent = icons.get(icon);
return () => return () =>
h(NIcon, null, { h(NIcon, null, {
default: () => h(iconComponent ? iconComponent : iconComponents.QuestionCircle20Regular), default: () => h(iconComponent ? iconComponent : iconComponents.QuestionCircle20Regular),
}) });
} }

View File

@ -11,13 +11,13 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { h, computed, type Component } from 'vue' import { h, computed, type Component } from "vue";
import { RouterLink, useRoute } from 'vue-router' import { RouterLink, useRoute } from "vue-router";
import { NIcon } from 'naive-ui' import { NIcon } from "naive-ui";
import type { MenuOption } from 'naive-ui' import type { MenuOption } from "naive-ui";
import * as iconComponents from '@vicons/fluent' import * as iconComponents from "@vicons/fluent";
const props = defineProps({ const props = defineProps({
inverted: { inverted: {
@ -26,27 +26,27 @@ const props = defineProps({
}, },
invertedBackgroundColor: { invertedBackgroundColor: {
type: String, type: String,
default: '#282c34', default: "#282c34",
}, },
collapsed: { collapsed: {
type: Boolean, type: Boolean,
default: false, default: false,
}, },
}) });
const style = computed(() => { const style = computed(() => {
return props.inverted ? { '--n-color': props.invertedBackgroundColor } : { '--n-color': '#ffffff' } return props.inverted ? { "--n-color": props.invertedBackgroundColor } : { "--n-color": "#ffffff" };
}) });
// MenuOptions // MenuOptions
const icons: Map<string, Component> = new Map(Object.entries(iconComponents)) const icons: Map<string, Component> = new Map(Object.entries(iconComponents));
function renderIcon(icon: string) { function renderIcon(icon: string) {
const iconComponent = icons.get(icon) const iconComponent = icons.get(icon);
return () => return () =>
h(NIcon, null, { h(NIcon, null, {
default: () => h(iconComponent ? iconComponent : iconComponents.QuestionCircle20Regular), default: () => h(iconComponent ? iconComponent : iconComponents.QuestionCircle20Regular),
}) });
} }
const menuOptions: MenuOption[] = [ const menuOptions: MenuOption[] = [
@ -56,48 +56,48 @@ const menuOptions: MenuOption[] = [
RouterLink, RouterLink,
{ {
to: { to: {
name: '404', name: "404",
params: { params: {
lang: 'zh-CN', lang: "zh-CN",
}, },
}, },
}, },
{ default: () => '回家' } { default: () => "回家" }
), ),
key: '404', key: "404",
icon: renderIcon('Home20Regular'), icon: renderIcon("Home20Regular"),
}, },
{ {
label: () => label: () =>
h( h(
RouterLink, RouterLink,
{ {
to: '/login', to: "/login",
}, },
{ default: () => '上班' } { default: () => "上班" }
), ),
key: '/login', key: "/login",
icon: renderIcon('Desktop20Regular'), icon: renderIcon("Desktop20Regular"),
}, },
{ {
label: () => label: () =>
h( h(
'a', "a",
{ {
href: 'http://zhouxy.xyz', href: "http://zhouxy.xyz",
target: '_blank', target: "_blank",
rel: 'noopenner noreferrer', rel: "noopenner noreferrer",
}, },
'ZhouXY' "ZhouXY"
), ),
key: 'hear-the-wind-sing', key: "hear-the-wind-sing",
icon: renderIcon('BookOpen20Filled'), icon: renderIcon("BookOpen20Filled"),
}, },
] ];
// ActiveKey // ActiveKey
const route = useRoute() const route = useRoute();
const activeKey = computed(() => { const activeKey = computed(() => {
return route.name return route.name;
}) });
</script> </script>

View File

@ -1,18 +1,20 @@
import { createApp } from 'vue' import { createApp } from "vue";
import { createPinia } from 'pinia' import { createPinia } from "pinia";
import App from './App.vue' import App from "./App.vue";
import router from './router' import router from "./router";
import './assets/main.css' import "./assets/main.css";
// 通用字体 // 通用字体
import 'vfonts/Lato.css' import "vfonts/Lato.css";
// 等宽字体 // 等宽字体
import 'vfonts/FiraCode.css' import "vfonts/FiraCode.css";
import { import {
// create naive ui // create naive ui
create, create,
// createDiscreteApi
createDiscreteApi,
// component // component
NButton, NButton,
NLayout, NLayout,
@ -27,11 +29,10 @@ import {
NInput, NInput,
NGrid, NGrid,
NGridItem, NGridItem,
NMessageProvider,
NCard, NCard,
NCheckbox, NCheckbox,
NCheckboxGroup, NCheckboxGroup,
} from 'naive-ui' } from "naive-ui";
const naive = create({ const naive = create({
components: [ components: [
@ -48,18 +49,29 @@ const naive = create({
NInput, NInput,
NGrid, NGrid,
NGridItem, NGridItem,
NMessageProvider,
NCard, NCard,
NCheckbox, NCheckbox,
NCheckboxGroup, NCheckboxGroup,
], ],
}) });
const app = createApp(App) const app = createApp(App);
app.use(createPinia()) app.use(createPinia());
app.use(router) app.use(router);
app.use(naive) app.use(naive);
app.mount('#app') app.mount("#app");
const { message, notification, dialog, loadingBar } = createDiscreteApi([
"message",
"dialog",
"notification",
"loadingBar",
]);
window.$message = message;
window.$notification = notification;
window.$dialog = dialog;
window.$loadingBar = loadingBar;

View File

@ -1,28 +1,28 @@
import { createRouter, createWebHistory } from 'vue-router' import { createRouter, createWebHistory } from "vue-router";
import MainPage from '../layouts/MainPage/MainPage.vue' import MainPage from "../layouts/MainPage/MainPage.vue";
import Login from '../views/Login/Login.vue' import Login from "../views/Login/Login.vue";
import Page404 from '../views/404/index.vue' import Page404 from "../views/404/index.vue";
const router = createRouter({ const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL), history: createWebHistory(import.meta.env.BASE_URL),
routes: [ routes: [
{ {
path: '/', path: "/",
component: MainPage, component: MainPage,
children: [ children: [
{ {
path: '404', path: "404",
name: '404', name: "404",
component: Page404, component: Page404,
}, },
], ],
}, },
{ {
path: '/login', path: "/login",
name: 'login', name: "login",
component: Login, component: Login,
}, },
], ],
}) });
export default router export default router;

View File

@ -1,12 +1,8 @@
import { ref, computed } from 'vue' import { ref, computed } from "vue";
import { defineStore } from 'pinia' import { defineStore } from "pinia";
export const useAccountStore = defineStore('account', () => { export const useAccountStore = defineStore("account", () => {
const count = ref(0) const token = ref<string | null>("0p978wqsetdgi9opw8e7s");
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubleCount, increment } return { token };
}) });

View File

@ -9,5 +9,5 @@ export const regexConsts = {
mobilePhone: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, mobilePhone: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
username: /^[\da-zA-Z_.@\\]{4,36}$/, username: /^[\da-zA-Z_.@\\]{4,36}$/,
password: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[\w\\!#$%&'*+\-/=?^`{|}~@()[]",\.;':><]{8,32}$/, password: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[\w\\!#$%&*+\-/=?^`{|}~@()[\]",.;':><]{8,32}$/,
} };

View File

@ -0,0 +1,14 @@
import type { PrincipalType } from "../PrincipalType";
export interface LoginByPasswordCommand {
principal: string;
password: string;
rememberMe: boolean;
principalType: PrincipalType | null;
}
export interface LoginByOTPCommand {
principal: string;
otp: string;
rememberMe: boolean;
}

View File

@ -0,0 +1,3 @@
export function getToken(): string {
return "g9-wes78dufgbcn9oup7bc";
}

View File

@ -0,0 +1,69 @@
import axios, { AxiosHeaders, type AxiosRequestConfig } from "axios";
import { useAccountStore } from "@/stores/account";
import { getToken } from "@/utils/auth";
const baseURL = import.meta.env.VITE_BASE_API;
const tokenName = import.meta.env.VITE_TOKEN_NAME;
// 创建axios实例
const service = axios.create({
baseURL, // api的base_url
timeout: 5000, // 请求超时时间
});
// request拦截器
service.interceptors.request.use(
(config: AxiosRequestConfig) => {
// Do something before request is sent
const accountStore = useAccountStore();
if (accountStore.token) {
const token: string = getToken();
(config.headers as AxiosHeaders).set(tokenName, token, true);
}
return config;
},
(error) => {
// Do something with request error
console.log(error); // for debug
Promise.reject(error);
}
);
// respone拦截器
service.interceptors.response.use(
(response) => response,
/**
* responsecodecode
* xmlhttprequest error
*/
// const res = response.data;
// if (res.code !== 20000) {
// Message({
// message: res.message,
// type: 'error',
// duration: 5 * 1000
// });
// // 50008:非法的token; 50012:其他客户端登录了; 50014:Token 过期了;
// if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
// MessageBox.confirm('你已被登出,可以取消继续留在该页面,或者重新登录', '确定登出', {
// confirmButtonText: '重新登录',
// cancelButtonText: '取消',
// type: 'warning'
// }).then(() => {
// store.dispatch('FedLogOut').then(() => {
// location.reload();// 为了重新实例化vue-router对象 避免bug
// });
// })
// }
// return Promise.reject('error');
// } else {
// return response.data;
// }
(err) => {
const responseData = err.response.data;
console.log("err", responseData); // for debug
return Promise.reject(responseData);
}
);
export default service;

View File

@ -6,11 +6,11 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { ref } from 'vue' import { ref } from "vue";
import LoginByPassword from './components/LoginByPassword.vue' import LoginByPassword from "./components/ChangePasswordByPassword.vue";
import LoginByOTP from './components/LoginByOTP.vue' import LoginByOTP from "./components/ChangePasswordByOTP.vue";
const loginByPassword = ref(true) const loginByPassword = ref(true);
</script> </script>
<style scoped> <style scoped>

View File

@ -81,24 +81,22 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { ref } from 'vue' import { ref } from "vue";
import type { FormInst, FormItemInst, FormItemRule, FormRules } from 'naive-ui' import type { FormInst, FormItemInst, FormItemRule, FormRules } from "naive-ui";
import { useMessage } from 'naive-ui'
interface LoginByPasswordCommand { interface LoginByPasswordCommand {
principal: string principal: string;
otp: string otp: string;
rememberMe: boolean rememberMe: boolean;
} }
const formRef = ref<FormInst | null>(null) const formRef = ref<FormInst | null>(null);
const rPasswordFormItemRef = ref<FormItemInst | null>(null) const rPasswordFormItemRef = ref<FormItemInst | null>(null);
const message = useMessage()
const model = ref<LoginByPasswordCommand>({ const model = ref<LoginByPasswordCommand>({
principal: '', principal: "",
otp: '', otp: "",
rememberMe: false, rememberMe: false,
}) });
const rules: FormRules = { const rules: FormRules = {
principal: [ principal: [
@ -106,45 +104,45 @@ const rules: FormRules = {
required: true, required: true,
validator(rule: FormItemRule, value: string) { validator(rule: FormItemRule, value: string) {
if (!value) { if (!value) {
return new Error('需要年龄') return new Error("需要年龄");
} else if (!/^\d*$/.test(value)) { } else if (!/^\d*$/.test(value)) {
return new Error('年龄应该为整数') return new Error("年龄应该为整数");
} else if (Number(value) < 18) { } else if (Number(value) < 18) {
return new Error('年龄应该超过十八岁') return new Error("年龄应该超过十八岁");
} }
return true return true;
}, },
trigger: ['input', 'blur'], trigger: ["input", "blur"],
}, },
], ],
otp: [ otp: [
{ {
required: true, required: true,
message: '请输入密码', message: "请输入密码",
}, },
], ],
} };
function handlePasswordInput() { function handlePasswordInput() {
if (model.value.rememberMe) { if (model.value.rememberMe) {
rPasswordFormItemRef.value?.validate({ trigger: 'password-input' }) rPasswordFormItemRef.value?.validate({ trigger: "password-input" });
} }
} }
function handleBtnLoginClick(e: MouseEvent) { function handleBtnLoginClick(e: MouseEvent) {
e.preventDefault() e.preventDefault();
formRef.value?.validate((errors) => { formRef.value?.validate((errors) => {
if (!errors) { if (!errors) {
message.success('验证成功') window.$message.success("验证成功");
} else { } else {
console.log(errors) console.log(errors);
message.error('验证失败') window.$message.error("验证失败");
} }
}) });
} }
function handleBtnGetOTPClick() { function handleBtnGetOTPClick() {
console.log('handleBtnGetOTPClick') console.log("handleBtnGetOTPClick");
} }
</script> </script>

View File

@ -63,26 +63,24 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { ref } from 'vue' import { ref } from "vue";
import type { FormInst, FormItemInst, FormItemRule, FormRules } from 'naive-ui' import type { FormInst, FormItemInst, FormItemRule, FormRules } from "naive-ui";
import { useMessage } from 'naive-ui' import type { PrincipalType } from "@/type/PrincipalType";
import type { PrincipalType } from '@/type/PrincipalType'
interface LoginByPasswordCommand { interface LoginByPasswordCommand {
principal: string principal: string;
password: string password: string;
rememberMe: boolean rememberMe: boolean;
principalType?: PrincipalType principalType?: PrincipalType;
} }
const formRef = ref<FormInst | null>(null) const formRef = ref<FormInst | null>(null);
const rPasswordFormItemRef = ref<FormItemInst | null>(null) const rPasswordFormItemRef = ref<FormItemInst | null>(null);
const message = useMessage()
const model = ref<LoginByPasswordCommand>({ const model = ref<LoginByPasswordCommand>({
principal: '', principal: "",
password: '', password: "",
rememberMe: false, rememberMe: false,
}) });
const rules: FormRules = { const rules: FormRules = {
principal: [ principal: [
@ -90,41 +88,41 @@ const rules: FormRules = {
required: true, required: true,
validator(rule: FormItemRule, value: string) { validator(rule: FormItemRule, value: string) {
if (!value) { if (!value) {
return new Error('需要年龄') return new Error("需要年龄");
} else if (!/^\d*$/.test(value)) { } else if (!/^\d*$/.test(value)) {
return new Error('年龄应该为整数') return new Error("年龄应该为整数");
} else if (Number(value) < 18) { } else if (Number(value) < 18) {
return new Error('年龄应该超过十八岁') return new Error("年龄应该超过十八岁");
} }
return true return true;
}, },
trigger: ['input', 'blur'], trigger: ["input", "blur"],
}, },
], ],
password: [ password: [
{ {
required: true, required: true,
message: '请输入密码', message: "请输入密码",
}, },
], ],
} };
function handlePasswordInput() { function handlePasswordInput() {
if (model.value.rememberMe) { if (model.value.rememberMe) {
rPasswordFormItemRef.value?.validate({ trigger: 'password-input' }) rPasswordFormItemRef.value?.validate({ trigger: "password-input" });
} }
} }
function handleBtnLoginClick(e: MouseEvent) { function handleBtnLoginClick(e: MouseEvent) {
e.preventDefault() e.preventDefault();
formRef.value?.validate((errors) => { formRef.value?.validate((errors) => {
if (!errors) { if (!errors) {
message.success('验证成功') window.$message.success("验证成功");
} else { } else {
console.log(errors) console.log(errors);
message.error('验证失败') window.$message.error("验证失败");
} }
}) });
} }
</script> </script>

View File

@ -6,11 +6,11 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { ref } from 'vue' import { ref } from "vue";
import LoginByPassword from './components/LoginByPassword.vue' import LoginByPassword from "./components/LoginByPassword.vue";
import LoginByOTP from './components/LoginByOTP.vue' import LoginByOTP from "./components/LoginByOTP.vue";
const loginByPassword = ref(true) const loginByPassword = ref(true);
</script> </script>
<style scoped> <style scoped>

View File

@ -38,7 +38,7 @@
class="txt-btn" class="txt-btn"
@click="handleBtnGetOTPClick" @click="handleBtnGetOTPClick"
size="large" size="large"
style="width 100%" style="width: 100%"
> >
获取验证码 获取验证码
</n-button> </n-button>
@ -81,24 +81,17 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { ref } from 'vue' import { ref } from "vue";
import type { FormInst, FormItemInst, FormItemRule, FormRules } from 'naive-ui' import type { FormInst, FormItemInst, FormItemRule, FormRules } from "naive-ui";
import { useMessage } from 'naive-ui' import type { LoginByOTPCommand } from "@/type/commands/LoginCommands";
interface LoginByPasswordCommand { const formRef = ref<FormInst | null>(null);
principal: string const rPasswordFormItemRef = ref<FormItemInst | null>(null);
otp: string const model = ref<LoginByOTPCommand>({
rememberMe: boolean principal: "",
} otp: "",
const formRef = ref<FormInst | null>(null)
const rPasswordFormItemRef = ref<FormItemInst | null>(null)
const message = useMessage()
const model = ref<LoginByPasswordCommand>({
principal: '',
otp: '',
rememberMe: false, rememberMe: false,
}) });
const rules: FormRules = { const rules: FormRules = {
principal: [ principal: [
@ -106,45 +99,45 @@ const rules: FormRules = {
required: true, required: true,
validator(rule: FormItemRule, value: string) { validator(rule: FormItemRule, value: string) {
if (!value) { if (!value) {
return new Error('需要年龄') return new Error("需要年龄");
} else if (!/^\d*$/.test(value)) { } else if (!/^\d*$/.test(value)) {
return new Error('年龄应该为整数') return new Error("年龄应该为整数");
} else if (Number(value) < 18) { } else if (Number(value) < 18) {
return new Error('年龄应该超过十八岁') return new Error("年龄应该超过十八岁");
} }
return true return true;
}, },
trigger: ['input', 'blur'], trigger: ["input", "blur"],
}, },
], ],
otp: [ otp: [
{ {
required: true, required: true,
message: '请输入密码', message: "请输入密码",
}, },
], ],
} };
function handlePasswordInput() { function handlePasswordInput() {
if (model.value.rememberMe) { if (model.value.rememberMe) {
rPasswordFormItemRef.value?.validate({ trigger: 'password-input' }) rPasswordFormItemRef.value?.validate({ trigger: "password-input" });
} }
} }
function handleBtnLoginClick(e: MouseEvent) { function handleBtnLoginClick(e: MouseEvent) {
e.preventDefault() e.preventDefault();
formRef.value?.validate((errors) => { formRef.value?.validate((errors) => {
if (!errors) { if (!errors) {
message.success('验证成功') window.$message.success("验证成功");
} else { } else {
console.log(errors) console.log(errors);
message.error('验证失败') window.$message.error("验证失败");
} }
}) });
} }
function handleBtnGetOTPClick() { function handleBtnGetOTPClick() {
console.log('handleBtnGetOTPClick') console.log("handleBtnGetOTPClick");
} }
</script> </script>

View File

@ -56,54 +56,58 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { ref } from 'vue' import { ref } from "vue";
import type { FormInst, FormItemInst, FormItemRule, FormRules } from 'naive-ui' import type { FormInst, FormItemInst } from "naive-ui";
import { useMessage } from 'naive-ui' import { PrincipalType, regexConsts } from "@/type/PrincipalType";
import { PrincipalType, regexConsts } from '@/type/PrincipalType' import type { LoginByPasswordCommand } from "@/type/commands/LoginCommands";
import { loginByPassword } from "@/api/account";
interface LoginByPasswordCommand { const formRef = ref<FormInst | null>(null);
principal: string const rPasswordFormItemRef = ref<FormItemInst | null>(null);
password: string
rememberMe: boolean
principalType: PrincipalType | null
}
const formRef = ref<FormInst | null>(null)
const rPasswordFormItemRef = ref<FormItemInst | null>(null)
const message = useMessage()
const model = ref<LoginByPasswordCommand>({ const model = ref<LoginByPasswordCommand>({
principal: '', principal: "",
password: '', password: "",
rememberMe: false, rememberMe: false,
principalType: null, principalType: null,
}) });
function handlePasswordInput() { function handlePasswordInput() {
if (model.value.rememberMe) { if (model.value.rememberMe) {
rPasswordFormItemRef.value?.validate({ trigger: 'password-input' }) rPasswordFormItemRef.value?.validate({ trigger: "password-input" });
} }
} }
function handleBtnLoginClick(e: MouseEvent) { function handleBtnLoginClick(e: MouseEvent) {
e.preventDefault() e.preventDefault();
const principal = model.value.principal const principal = model.value.principal;
const password = model.value.password const password = model.value.password;
if (regexConsts.email.test(principal)) { if (regexConsts.email.test(principal)) {
model.value.principalType = PrincipalType.EMAIL model.value.principalType = PrincipalType.EMAIL;
} else if (regexConsts.mobilePhone.test(principal)) { } else if (regexConsts.mobilePhone.test(principal)) {
model.value.principalType = PrincipalType.MOBILE_PHONE model.value.principalType = PrincipalType.MOBILE_PHONE;
} else if (regexConsts.username.test(principal)) { } else if (regexConsts.username.test(principal)) {
model.value.principalType = PrincipalType.USERNAME model.value.principalType = PrincipalType.USERNAME;
} else { } else {
message.error('请输入用户名、电子邮箱或手机号') window.$message.error("请输入用户名、电子邮箱或手机号");
return return;
} }
if (!regexConsts.password.test(password)) { if (!regexConsts.password.test(password)) {
message.error('输入的密码不符合要求') window.$message.error("输入的密码不符合要求");
return;
} }
loginByPassword(model.value)
.then(({ data }) => {
if (data.status === 2000000) {
window.$message.success("登录成功");
} else {
Promise.reject(data);
}
})
.catch((err) => {
window.$message.error(err.message);
});
} }
</script> </script>

View File

@ -1,17 +1,17 @@
import { fileURLToPath, URL } from 'node:url' import { fileURLToPath, URL } from "node:url";
import { defineConfig } from 'vite' import { defineConfig } from "vite";
import vue from '@vitejs/plugin-vue' import vue from "@vitejs/plugin-vue";
// https://vitejs.dev/config/ // https://vitejs.dev/config/
export default defineConfig({ export default defineConfig({
plugins: [vue()], plugins: [vue()],
resolve: { resolve: {
alias: { alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)), "@": fileURLToPath(new URL("./src", import.meta.url)),
}, },
}, },
server: { server: {
port: 8888, port: 8888,
}, },
}) });