This commit is contained in:
2024-11-05 11:43:27 +08:00
parent 7f8aeebb1e
commit 64ae879aee
4 changed files with 110 additions and 113 deletions

View File

@@ -1,4 +1,4 @@
import type { Dict } from './../../api/interface/index'; import type { Dict } from './../../api/interface/index'
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import piniaPersistConfig from '@/stores/helper/persist' import piniaPersistConfig from '@/stores/helper/persist'
import { DICT_STORE_KEY } from '@/stores/constant' import { DICT_STORE_KEY } from '@/stores/constant'
@@ -6,36 +6,24 @@ import { DICT_STORE_KEY } from '@/stores/constant'
//import dictData from '@/api/system/dictData' //import dictData from '@/api/system/dictData'
import { getDictList } from '@/api/user/login.ts' import { getDictList } from '@/api/user/login.ts'
// 初始值设为空数组
let dictData: Dict[] = [];
async function fetchDictData() {
try {
const response = await getDictList();
dictData = response.data as unknown as Dict[];
console.log('Fetched dictionary data:', dictData);
} catch (error) {
console.error('Failed to fetch dictionary data:', error);
}
}
fetchDictData();
export const useDictStore = defineStore({ export const useDictStore = defineStore({
id: DICT_STORE_KEY, id: DICT_STORE_KEY,
state: () => ({ state: () => ({
dictData, dictData: [],
}), }),
getters: {}, getters: {},
actions: { actions: {
// 获取字典数据数组,如果为空则返回空数组 // 获取字典数据数组,如果为空则返回空数组
getDictData(code: string) { getDictData(code: string) {
const dict = this.dictData.find(item => item.code === code ) if (!this.dictData.length) {
return dict?.children || []; return []
}
const dict = this.dictData.find(item => item.code === code)
return dict?.children || []
}, },
// 初始化获取全部字典数据并缓存 // 初始化获取全部字典数据并缓存
async initDictData() { async initDictData(initData: Dict[]) {
await fetchDictData(); this.dictData = initData
}, },
}, },
persist: piniaPersistConfig(DICT_STORE_KEY), persist: piniaPersistConfig(DICT_STORE_KEY),

View File

@@ -1,146 +1,153 @@
<template> <template>
<el-form <el-form
ref="loginFormRef" ref='loginFormRef'
:model="loginForm" :model='loginForm'
:rules="loginRules" :rules='loginRules'
size="large" size='large'
> >
<el-form-item prop="username"> <el-form-item prop='username'>
<el-input v-model="loginForm.username" placeholder="用户名"> <el-input v-model='loginForm.username' placeholder='用户名'>
<template #prefix> <template #prefix>
<el-icon class="el-input__icon"> <el-icon class='el-input__icon'>
<user /> <user />
</el-icon> </el-icon>
</template> </template>
</el-input> </el-input>
</el-form-item> </el-form-item>
<el-form-item prop="password"> <el-form-item prop='password'>
<el-input <el-input
v-model="loginForm.password" v-model='loginForm.password'
type="password" type='password'
placeholder="密码" placeholder='密码'
show-password show-password
autocomplete="new-password" autocomplete='new-password'
> >
<template #prefix> <template #prefix>
<el-icon class="el-input__icon"> <el-icon class='el-input__icon'>
<lock /> <lock />
</el-icon> </el-icon>
</template> </template>
</el-input> </el-input>
</el-form-item> </el-form-item>
</el-form> </el-form>
<div class="login-btn"> <div class='login-btn'>
<el-button <el-button
:icon="UserFilled" :icon='UserFilled'
round round
size="large" size='large'
type="primary" type='primary'
:loading="loading" :loading='loading'
@click="login(loginFormRef)" @click='login(loginFormRef)'
> >
登录 登录
</el-button> </el-button>
<el-button <el-button
:icon="CircleClose" :icon='CircleClose'
round round
size="large" size='large'
@click="resetForm(loginFormRef)" @click='resetForm(loginFormRef)'
> >
重置 重置
</el-button> </el-button>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang='ts'>
import { useRouter } from "vue-router"; import { useRouter } from 'vue-router'
import { HOME_URL } from "@/config"; import { HOME_URL } from '@/config'
import { getTimeState } from "@/utils"; import { getTimeState } from '@/utils'
import { Login } from "@/api/interface"; import { Dict, Login } from '@/api/interface'
import { ElNotification } from "element-plus"; import { ElNotification } from 'element-plus'
import { loginApi } from "@/api/user/login"; import { getDictList, loginApi } from '@/api/user/login'
import { useUserStore } from "@/stores/modules/user"; import { useUserStore } from '@/stores/modules/user'
import { useTabsStore } from "@/stores/modules/tabs"; import { useTabsStore } from '@/stores/modules/tabs'
import { useKeepAliveStore } from "@/stores/modules/keepAlive"; import { useKeepAliveStore } from '@/stores/modules/keepAlive'
import { initDynamicRouter } from "@/routers/modules/dynamicRouter"; import { initDynamicRouter } from '@/routers/modules/dynamicRouter'
import { CircleClose, UserFilled } from "@element-plus/icons-vue"; import { CircleClose, UserFilled } from '@element-plus/icons-vue'
import { useAuthStore } from "@/stores/modules/auth"; import { useAuthStore } from '@/stores/modules/auth'
import type { ElForm } from "element-plus"; import type { ElForm } from 'element-plus'
import md5 from "md5"; import md5 from 'md5'
const authStore = useAuthStore();
const router = useRouter(); const authStore = useAuthStore()
const userStore = useUserStore(); const router = useRouter()
const tabsStore = useTabsStore(); const userStore = useUserStore()
const keepAliveStore = useKeepAliveStore(); const tabsStore = useTabsStore()
const keepAliveStore = useKeepAliveStore()
import { useDictStore } from '@/stores/modules/dict'
const dictStore = useDictStore()
type FormInstance = InstanceType<typeof ElForm>; type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>(); const loginFormRef = ref<FormInstance>()
const loginRules = reactive({ const loginRules = reactive({
username: [{ required: true, message: "请输入用户名", trigger: "blur" }], username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
password: [{ required: true, message: "请输入密码", trigger: "blur" }], password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
}); })
const loading = ref(false); const loading = ref(false)
const loginForm = reactive<Login.ReqLoginForm>({ const loginForm = reactive<Login.ReqLoginForm>({
username: "", username: '',
password: "", password: '',
}); })
// login // login
const login = (formEl: FormInstance | undefined) => { const login = (formEl: FormInstance | undefined) => {
if (!formEl) return; if (!formEl) return
formEl.validate(async (valid) => { formEl.validate(async (valid) => {
if (!valid) return; if (!valid) return
loading.value = true; loading.value = true
try { try {
// 1.执行登录接口 // 1.执行登录接口
const { data } = await loginApi({ const { data } = await loginApi({
...loginForm, ...loginForm,
password: md5(loginForm.password), password: md5(loginForm.password),
}); })
userStore.setToken(data.accessToken); userStore.setToken(data.accessToken)
const response = await getDictList()
const dictData = response.data as unknown as Dict[]
await dictStore.initDictData(dictData)
// 2.添加动态路由 // 2.添加动态路由
await initDynamicRouter(); await initDynamicRouter()
// 3.清空 tabs、keepAlive 数据 // 3.清空 tabs、keepAlive 数据
tabsStore.setTabs([]); tabsStore.setTabs([])
keepAliveStore.setKeepAliveName([]); keepAliveStore.setKeepAliveName([])
// 4.跳转到首页 // 4.跳转到首页
router.push(HOME_URL); router.push(HOME_URL)
// 5.登录默认不显示菜单和导航栏 // 5.登录默认不显示菜单和导航栏
authStore.resetAuthStore(); authStore.resetAuthStore()
ElNotification({ ElNotification({
title: getTimeState(), title: getTimeState(),
message: "登录成功", message: '登录成功',
type: "success", type: 'success',
duration: 3000, duration: 3000,
}); })
} finally { } finally {
loading.value = false; loading.value = false
} }
}); })
}; }
// resetForm // resetForm
const resetForm = (formEl: FormInstance | undefined) => { const resetForm = (formEl: FormInstance | undefined) => {
if (!formEl) return; if (!formEl) return
formEl.resetFields(); formEl.resetFields()
}; }
onMounted(() => { onMounted(() => {
// 监听 enter 事件(调用登录) // 监听 enter 事件(调用登录)
document.onkeydown = (e: KeyboardEvent) => { document.onkeydown = (e: KeyboardEvent) => {
e = (window.event as KeyboardEvent) || e; e = (window.event as KeyboardEvent) || e
if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") { if (e.code === 'Enter' || e.code === 'enter' || e.code === 'NumpadEnter') {
if (loading.value) return; if (loading.value) return
login(loginFormRef.value); login(loginFormRef.value)
} }
}; }
}); })
</script> </script>
<style scoped lang="scss"> <style scoped lang='scss'>
@import "../index.scss"; @import "../index.scss";
</style> </style>

View File

@@ -20,6 +20,7 @@
<script setup lang="ts" name="login"> <script setup lang="ts" name="login">
import LoginForm from "./components/LoginForm.vue"; import LoginForm from "./components/LoginForm.vue";
const title = import.meta.env.VITE_GLOB_APP_TITLE; const title = import.meta.env.VITE_GLOB_APP_TITLE;
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">

View File

@@ -169,6 +169,7 @@
import { useDictStore } from '@/stores/modules/dict' import { useDictStore } from '@/stores/modules/dict'
import { getDictList } from '@/api/user/login.ts' import { getDictList } from '@/api/user/login.ts'
const dictStore = useDictStore() const dictStore = useDictStore()
// 定义弹出组件元信息 // 定义弹出组件元信息
const dialogFormRef = ref() const dialogFormRef = ref()
const options = [ const options = [
@@ -269,7 +270,7 @@ import { getDictList } from '@/api/user/login.ts'
const open = (sign: string, data: Dict.ResDictPq) => { const open = (sign: string, data: Dict.ResDictPq) => {
titleType.value = sign titleType.value = sign
dialogVisible.value = true dialogVisible.value = true
console.log('123456',dictStore.getDictData('High_Cate'))
if (data.id) { if (data.id) {
formContent.value = { ...data } formContent.value = { ...data }
} else { } else {