feat: refactoring API

This commit is contained in:
kailong321200875 2022-06-25 21:56:24 +08:00
parent 43518532f1
commit 37b75839a5
29 changed files with 198 additions and 339 deletions

View File

@ -516,9 +516,7 @@ export default [
const { roleName } = query const { roleName } = query
return { return {
code: result_code, code: result_code,
data: { data: roleName === 'admin' ? adminList : testList
list: roleName === 'admin' ? adminList : testList
}
} }
} }
} }

View File

@ -1,9 +0,0 @@
export interface IUserModel {
user_name: string
password: string
check_password: string
is_admin: number
code?: string | number
token?: string
refreshToken?: string
}

View File

@ -3,11 +3,13 @@ import { useAxios } from '@/hooks/web/useAxios'
const request = useAxios() const request = useAxios()
// 获取所有字典 // 获取所有字典
export const getDictApi = () => { export const getDictApi = async (): Promise<IResponse> => {
return request.get({ url: '/dict/list' }) const res = await request.get({ url: '/dict/list' })
return res && res.data
} }
// 模拟获取某个字典 // 模拟获取某个字典
export const getDictOneApi = () => { export const getDictOneApi = async (): Promise<IResponse> => {
return request.get({ url: '/dict/one' }) const res = await request.get({ url: '/dict/one' })
return res && res.data
} }

View File

@ -8,18 +8,22 @@ import type {
const request = useAxios() const request = useAxios()
export const getCountApi = () => { export const getCountApi = async (): Promise<IResponse<AnalysisTotalTypes[]>> => {
return request.get<AnalysisTotalTypes>({ url: '/analysis/total' }) const res = await request.get({ url: '/analysis/total' })
return res && res.data
} }
export const getUserAccessSourceApi = () => { export const getUserAccessSourceApi = async (): Promise<IResponse<UserAccessSource[]>> => {
return request.get<UserAccessSource[]>({ url: '/analysis/userAccessSource' }) const res = await request.get({ url: '/analysis/userAccessSource' })
return res && res.data
} }
export const getWeeklyUserActivityApi = () => { export const getWeeklyUserActivityApi = async (): Promise<IResponse<WeeklyUserActivity[]>> => {
return request.get<WeeklyUserActivity[]>({ url: '/analysis/weeklyUserActivity' }) const res = await request.get({ url: '/analysis/weeklyUserActivity' })
return res && res.data
} }
export const getMonthlySalesApi = () => { export const getMonthlySalesApi = async (): Promise<IResponse<MonthlySales[]>> => {
return request.get<MonthlySales[]>({ url: '/analysis/monthlySales' }) const res = await request.get({ url: '/analysis/monthlySales' })
return res && res.data
} }

View File

@ -3,22 +3,27 @@ import type { WorkplaceTotal, Project, Dynamic, Team, RadarData } from './types'
const request = useAxios() const request = useAxios()
export const getCountApi = () => { export const getCountApi = async (): Promise<IResponse<WorkplaceTotal>> => {
return request.get<WorkplaceTotal>({ url: '/workplace/total' }) const res = await request.get({ url: '/workplace/total' })
return res && res.data
} }
export const getProjectApi = () => { export const getProjectApi = async (): Promise<IResponse<Project>> => {
return request.get<Project[]>({ url: '/workplace/project' }) const res = await request.get({ url: '/workplace/project' })
return res && res.data
} }
export const getDynamicApi = () => { export const getDynamicApi = async (): Promise<IResponse<Dynamic[]>> => {
return request.get<Dynamic[]>({ url: '/workplace/dynamic' }) const res = await request.get({ url: '/workplace/dynamic' })
return res && res.data
} }
export const getTeamApi = () => { export const getTeamApi = async (): Promise<IResponse<Team[]>> => {
return request.get<Team[]>({ url: '/workplace/team' }) const res = await request.get({ url: '/workplace/team' })
return res && res.data
} }
export const getRadarApi = () => { export const getRadarApi = async (): Promise<IResponse<RadarData[]>> => {
return request.get<RadarData[]>({ url: '/workplace/radar' }) const res = await request.get({ url: '/workplace/radar' })
return res && res.data
} }

View File

@ -1,19 +1,20 @@
import { useAxios } from '@/hooks/web/useAxios' import { useAxios } from '@/hooks/web/useAxios'
import type { UserType } from './types' import type { UserType } from './types'
import { IUserModel } from '@/api-types/user'
interface RoleParams {
roleName: string
}
const request = useAxios() const request = useAxios()
export const loginApi = async (data: Pick<IUserModel, 'user_name' | 'password'>) => { export const loginApi = async (data: UserType): Promise<IResponse<UserType>> => {
const res = await request.post<IResponse<IUserModel>>({ const res = await request.post({ url: '/user/login', data })
url: '/user/login',
data
})
return res && res.data return res && res.data
} }
export const loginOutApi = () => { export const loginOutApi = async (): Promise<IResponse> => {
return request.get({ url: '/user/loginOut' }) const res = await request.get({ url: '/user/loginOut' })
return res && res.data
} }
export const getUserListApi = ({ params }: AxiosConfig) => { export const getUserListApi = ({ params }: AxiosConfig) => {
@ -23,14 +24,14 @@ export const getUserListApi = ({ params }: AxiosConfig) => {
}>({ url: '/user/list', params }) }>({ url: '/user/list', params })
} }
export const getAdminRoleApi = ({ params }) => { export const getAdminRoleApi = async (
return request.get<{ params: RoleParams
list: AppCustomRouteRecordRaw[] ): Promise<IResponse<AppCustomRouteRecordRaw[]>> => {
}>({ url: '/role/list', params }) const res = await request.get({ url: '/role/list', params })
return res && res.data
} }
export const getTestRoleApi = ({ params }) => { export const getTestRoleApi = async (params: RoleParams): Promise<IResponse<string[]>> => {
return request.get<{ const res = await request.get({ url: '/role/list', params })
list: string[] return res && res.data
}>({ url: '/role/list', params })
} }

View File

@ -1,21 +0,0 @@
import { useAxios } from '@/hooks/web/useAxios'
import { IUserModel } from '@/api-types/user'
const request = useAxios()
interface ICodeModel {
url: string
uuid: string
}
export const getCodeApi = async (): Promise<IResponse<ICodeModel>> => {
const res = await request.get({ url: 'user/captcha' })
return res && res.data
}
export const registerApi = async (
data: Omit<IUserModel, 'is_admin'>
): Promise<IResponse<IUserModel>> => {
const res = await request.post({ url: 'user/register', data })
return res && res.data
}

View File

@ -3,21 +3,22 @@ import type { TableData } from './types'
const request = useAxios() const request = useAxios()
export const getTableListApi = ({ params }) => { export const getTableListApi = async (params: any): Promise<IResponse> => {
return request.get<{ const res = await request.get({ url: '/example/list', params })
total: number return res && res.data
list: TableData[]
}>({ url: '/example/list', params })
} }
export const saveTableApi = ({ data }) => { export const saveTableApi = async (data: Partial<TableData>): Promise<IResponse> => {
return request.post<TableData>({ url: '/example/save', data }) const res = await request.post({ url: '/example/save', data })
return res && res.data
} }
export const getTableDetApi = ({ params }) => { export const getTableDetApi = async (id: string): Promise<IResponse<TableData>> => {
return request.get<TableData>({ url: '/example/detail', params }) const res = await request.get({ url: '/example/detail', params: { id } })
return res && res.data
} }
export const delTableListApi = ({ data }) => { export const delTableListApi = async (ids: string[] | number[]): Promise<IResponse> => {
return request.post({ url: '/example/delete', data }) const res = await request.post({ url: '/example/delete', data: { ids } })
return res && res.data
} }

View File

@ -14,7 +14,7 @@ const config: {
*/ */
base_url: { base_url: {
// 开发环境接口前缀 // 开发环境接口前缀
base: '/api', base: '',
// 打包开发环境接口前缀 // 打包开发环境接口前缀
dev: '', dev: '',

View File

@ -1,16 +1,22 @@
import { Table, TableExpose } from '@/components/Table' import { Table, TableExpose } from '@/components/Table'
import { ElTable, ElMessageBox, ElMessage } from 'element-plus' import { ElTable, ElMessageBox, ElMessage } from 'element-plus'
import { ref, reactive, watch, computed, unref, nextTick } from 'vue' import { ref, reactive, watch, computed, unref, nextTick } from 'vue'
import { AxiosPromise } from 'axios'
import { get } from 'lodash-es' import { get } from 'lodash-es'
import type { TableProps } from '@/components/Table/src/types' import type { TableProps } from '@/components/Table/src/types'
import { useI18n } from '@/hooks/web/useI18n' import { useI18n } from '@/hooks/web/useI18n'
const { t } = useI18n() const { t } = useI18n()
interface UseTableConfig<T, L> { interface TableResponse<T = any> {
getListApi: (option: L) => AxiosPromise<T> total: number
delListApi?: (option: AxiosConfig) => AxiosPromise<unknown> list: T[]
pageNumber: number
pageSize: number
}
interface UseTableConfig<T = any> {
getListApi: (option: any) => Promise<IResponse<TableResponse<T>>>
delListApi?: (option: any) => Promise<IResponse>
// 返回数据格式配置 // 返回数据格式配置
response: { response: {
list: string list: string
@ -19,20 +25,18 @@ interface UseTableConfig<T, L> {
props?: TableProps props?: TableProps
} }
interface TableObject<K, L> { interface TableObject<T = any> {
pageSize: number pageSize: number
currentPage: number currentPage: number
total: number total: number
tableList: K[] tableList: T[]
paramsObj: L params: any
loading: boolean loading: boolean
currentRow: Nullable<K> currentRow: Nullable<T>
} }
export const useTable = <T, K, L extends AxiosConfig = AxiosConfig>( export const useTable = <T = any>(config?: UseTableConfig<T>) => {
config?: UseTableConfig<T, L> const tableObject = reactive<TableObject<T>>({
) => {
const tableObject = reactive<TableObject<K, L>>({
// 页数 // 页数
pageSize: 10, pageSize: 10,
// 当前页 // 当前页
@ -42,7 +46,7 @@ export const useTable = <T, K, L extends AxiosConfig = AxiosConfig>(
// 表格数据 // 表格数据
tableList: [], tableList: [],
// AxiosConfig 配置 // AxiosConfig 配置
paramsObj: {} as L, params: {},
// 加载中 // 加载中
loading: true, loading: true,
// 当前行的数据 // 当前行的数据
@ -51,11 +55,9 @@ export const useTable = <T, K, L extends AxiosConfig = AxiosConfig>(
const paramsObj = computed(() => { const paramsObj = computed(() => {
return { return {
params: { ...tableObject.params,
...tableObject.paramsObj.params, pageSize: tableObject.pageSize,
pageSize: tableObject.pageSize, pageIndex: tableObject.currentPage
pageIndex: tableObject.currentPage
}
} }
}) })
@ -99,8 +101,8 @@ export const useTable = <T, K, L extends AxiosConfig = AxiosConfig>(
return table return table
} }
const delData = async (paramsObj: AxiosConfig, ids: string[] | number[]) => { const delData = async (ids: string[] | number[]) => {
const res = await (config?.delListApi && config?.delListApi(paramsObj)) const res = await (config?.delListApi && config?.delListApi(ids))
if (res) { if (res) {
ElMessage.success(t('common.delSuccess')) ElMessage.success(t('common.delSuccess'))
@ -117,22 +119,12 @@ export const useTable = <T, K, L extends AxiosConfig = AxiosConfig>(
} }
} }
const methods: { const methods = {
setProps: (props: Recordable) => void
getList: () => Promise<void>
setColumn: (columnProps: TableSetPropsType[]) => void
setSearchParams: (data: Recordable) => void
getSelections: () => Promise<K[]>
delList: (ids: string[] | number[], multiple: boolean, message?: boolean) => Promise<void>
} = {
getList: async () => { getList: async () => {
tableObject.loading = true tableObject.loading = true
const res = await config const res = await config?.getListApi(unref(paramsObj)).finally(() => {
?.getListApi(unref(paramsObj) as unknown as L) tableObject.loading = false
.catch(() => {}) })
.finally(() => {
tableObject.loading = false
})
if (res) { if (res) {
tableObject.tableList = get(res.data || {}, config?.response.list as string) tableObject.tableList = get(res.data || {}, config?.response.list as string)
tableObject.total = get(res.data || {}, config?.response?.total as string) || 0 tableObject.total = get(res.data || {}, config?.response?.total as string) || 0
@ -148,17 +140,15 @@ export const useTable = <T, K, L extends AxiosConfig = AxiosConfig>(
}, },
getSelections: async () => { getSelections: async () => {
const table = await getTable() const table = await getTable()
return (table?.selections || []) as K[] return (table?.selections || []) as T[]
}, },
// 与Search组件结合 // 与Search组件结合
setSearchParams: (data: Recordable) => { setSearchParams: (data: Recordable) => {
tableObject.currentPage = 1 tableObject.currentPage = 1
tableObject.paramsObj = Object.assign(tableObject.paramsObj, { tableObject.params = Object.assign(tableObject.params, {
params: { pageSize: tableObject.pageSize,
pageSize: tableObject.pageSize, pageIndex: tableObject.currentPage,
pageIndex: tableObject.currentPage, ...data
...data
}
}) })
methods.getList() methods.getList()
}, },
@ -176,23 +166,16 @@ export const useTable = <T, K, L extends AxiosConfig = AxiosConfig>(
return return
} }
} }
const paramsObj: AxiosConfig = {
data: {
ids
}
}
if (message) { if (message) {
ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), { ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), {
confirmButtonText: t('common.delOk'), confirmButtonText: t('common.delOk'),
cancelButtonText: t('common.delCancel'), cancelButtonText: t('common.delCancel'),
type: 'warning' type: 'warning'
}).then(async () => {
await delData(ids)
}) })
.then(async () => {
await delData(paramsObj, ids)
})
.catch(() => {})
} else { } else {
await delData(paramsObj, ids) await delData(ids)
} }
} }
} }

View File

@ -1,3 +1,7 @@
import { useI18n } from '@/hooks/web/useI18n'
const { t } = useI18n()
type Callback = (error?: string | Error | undefined) => void type Callback = (error?: string | Error | undefined) => void
interface LengthRange { interface LengthRange {
@ -7,10 +11,10 @@ interface LengthRange {
} }
export const useValidator = () => { export const useValidator = () => {
const required = (message: string) => { const required = (message?: string) => {
return { return {
required: true, required: true,
message message: message || t('common.required')
} }
} }

View File

@ -1,9 +0,0 @@
import { useI18n } from '@/hooks/web/useI18n'
const { t } = useI18n()
// 必填项
export const required = {
required: true,
message: t('common.required')
}

View File

@ -4,9 +4,11 @@ import { useI18n } from '@/hooks/web/useI18n'
import { reactive, unref } from 'vue' import { reactive, unref } from 'vue'
import { Form } from '@/components/Form' import { Form } from '@/components/Form'
import { ElFormItem, ElInput, ElButton } from 'element-plus' import { ElFormItem, ElInput, ElButton } from 'element-plus'
import { required } from '@/utils/formRules' import { useValidator } from '@/hooks/web/useValidator'
import { useForm } from '@/hooks/web/useForm' import { useForm } from '@/hooks/web/useForm'
const { required } = useValidator()
const { t } = useI18n() const { t } = useI18n()
const data = reactive({ const data = reactive({
@ -53,11 +55,11 @@ const form = reactive({
}) })
const rules = reactive({ const rules = reactive({
username: [required], username: [required()],
nickName: [required], nickName: [required()],
phone: [required], phone: [required()],
email: [required], email: [required()],
addr: [required] addr: [required()]
}) })
const { register, elFormRef } = useForm() const { register, elFormRef } = useForm()

View File

@ -4,7 +4,9 @@ import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n' import { useI18n } from '@/hooks/web/useI18n'
import { reactive, unref, ref } from 'vue' import { reactive, unref, ref } from 'vue'
import { ElButton } from 'element-plus' import { ElButton } from 'element-plus'
import { required } from '@/utils/formRules' import { useValidator } from '@/hooks/web/useValidator'
const { required } = useValidator()
const { t } = useI18n() const { t } = useI18n()
@ -14,7 +16,7 @@ const schema = reactive<FormSchema[]>([
label: t('formDemo.input'), label: t('formDemo.input'),
component: 'Input', component: 'Input',
formItemProps: { formItemProps: {
rules: [required] rules: [required()]
} }
}, },
{ {

View File

@ -5,7 +5,9 @@ import { useI18n } from '@/hooks/web/useI18n'
import { useForm } from '@/hooks/web/useForm' import { useForm } from '@/hooks/web/useForm'
import { reactive, unref, ref } from 'vue' import { reactive, unref, ref } from 'vue'
import { ElButton } from 'element-plus' import { ElButton } from 'element-plus'
import { required } from '@/utils/formRules' import { useValidator } from '@/hooks/web/useValidator'
const { required } = useValidator()
const { t } = useI18n() const { t } = useI18n()
@ -15,7 +17,7 @@ const schema = reactive<FormSchema[]>([
label: t('formDemo.input'), label: t('formDemo.input'),
component: 'Input', component: 'Input',
formItemProps: { formItemProps: {
rules: [required] rules: [required()]
} }
}, },
{ {

View File

@ -3,9 +3,11 @@ import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n' import { useI18n } from '@/hooks/web/useI18n'
import { Search } from '@/components/Search' import { Search } from '@/components/Search'
import { reactive, ref, unref } from 'vue' import { reactive, ref, unref } from 'vue'
import { required } from '@/utils/formRules' import { useValidator } from '@/hooks/web/useValidator'
import { ElButton } from 'element-plus' import { ElButton } from 'element-plus'
const { required } = useValidator()
const { t } = useI18n() const { t } = useI18n()
const schema = reactive<FormSchema[]>([ const schema = reactive<FormSchema[]>([
@ -14,7 +16,7 @@ const schema = reactive<FormSchema[]>([
label: t('formDemo.input'), label: t('formDemo.input'),
component: 'Input', component: 'Input',
formItemProps: { formItemProps: {
rules: [required] rules: [required()]
} }
}, },
{ {
@ -69,7 +71,7 @@ const schema = reactive<FormSchema[]>([
label: t('formDemo.input'), label: t('formDemo.input'),
component: 'Input', component: 'Input',
formItemProps: { formItemProps: {
rules: [required] rules: [required()]
} }
}, },
{ {
@ -77,7 +79,7 @@ const schema = reactive<FormSchema[]>([
label: t('formDemo.input'), label: t('formDemo.input'),
component: 'Input', component: 'Input',
formItemProps: { formItemProps: {
rules: [required] rules: [required()]
} }
}, },
{ {
@ -85,7 +87,7 @@ const schema = reactive<FormSchema[]>([
label: t('formDemo.input'), label: t('formDemo.input'),
component: 'Input', component: 'Input',
formItemProps: { formItemProps: {
rules: [required] rules: [required()]
} }
}, },
{ {
@ -93,7 +95,7 @@ const schema = reactive<FormSchema[]>([
label: t('formDemo.input'), label: t('formDemo.input'),
component: 'Input', component: 'Input',
formItemProps: { formItemProps: {
rules: [required] rules: [required()]
} }
}, },
{ {
@ -101,7 +103,7 @@ const schema = reactive<FormSchema[]>([
label: t('formDemo.input'), label: t('formDemo.input'),
component: 'Input', component: 'Input',
formItemProps: { formItemProps: {
rules: [required] rules: [required()]
} }
}, },
{ {
@ -109,7 +111,7 @@ const schema = reactive<FormSchema[]>([
label: t('formDemo.input'), label: t('formDemo.input'),
component: 'Input', component: 'Input',
formItemProps: { formItemProps: {
rules: [required] rules: [required()]
} }
}, },
{ {
@ -117,7 +119,7 @@ const schema = reactive<FormSchema[]>([
label: t('formDemo.input'), label: t('formDemo.input'),
component: 'Input', component: 'Input',
formItemProps: { formItemProps: {
rules: [required] rules: [required()]
} }
}, },
{ {
@ -125,7 +127,7 @@ const schema = reactive<FormSchema[]>([
label: t('formDemo.input'), label: t('formDemo.input'),
component: 'Input', component: 'Input',
formItemProps: { formItemProps: {
rules: [required] rules: [required()]
} }
}, },
{ {
@ -133,7 +135,7 @@ const schema = reactive<FormSchema[]>([
label: t('formDemo.input'), label: t('formDemo.input'),
component: 'Input', component: 'Input',
formItemProps: { formItemProps: {
rules: [required] rules: [required()]
} }
}, },
{ {
@ -141,7 +143,7 @@ const schema = reactive<FormSchema[]>([
label: t('formDemo.input'), label: t('formDemo.input'),
component: 'Input', component: 'Input',
formItemProps: { formItemProps: {
rules: [required] rules: [required()]
} }
}, },
{ {
@ -149,7 +151,7 @@ const schema = reactive<FormSchema[]>([
label: t('formDemo.input'), label: t('formDemo.input'),
component: 'Input', component: 'Input',
formItemProps: { formItemProps: {
rules: [required] rules: [required()]
} }
} }
]) ])

View File

@ -65,12 +65,12 @@ const loading = ref(true)
let tableDataList = ref<TableData[]>([]) let tableDataList = ref<TableData[]>([])
const getTableList = async (params?: Params) => { const getTableList = async (params?: Params) => {
const res = await getTableListApi({ const res = await getTableListApi(
params: params || { params || {
pageIndex: 1, pageIndex: 1,
pageSize: 10 pageSize: 10
} }
}) )
.catch(() => {}) .catch(() => {})
.finally(() => { .finally(() => {
loading.value = false loading.value = false

View File

@ -62,13 +62,7 @@ const columns = reactive<TableColumn[]>([
} }
]) ])
const { register, tableObject, methods } = useTable< const { register, tableObject, methods } = useTable<TableData>({
{
total: number
list: TableData[]
},
TableData
>({
getListApi: getTableListApi, getListApi: getTableListApi,
response: { response: {
list: 'list', list: 'list',

View File

@ -8,13 +8,7 @@ import { ref, h, reactive, unref } from 'vue'
import { ElTag, ElButton } from 'element-plus' import { ElTag, ElButton } from 'element-plus'
import { useTable } from '@/hooks/web/useTable' import { useTable } from '@/hooks/web/useTable'
const { register, tableObject, methods } = useTable< const { register, tableObject, methods } = useTable<TableData>({
{
total: number
list: TableData[]
},
TableData
>({
getListApi: getTableListApi, getListApi: getTableListApi,
response: { response: {
list: 'list', list: 'list',

View File

@ -13,13 +13,7 @@ import Write from './components/Write.vue'
import Detail from './components/Detail.vue' import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas' import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
const { register, tableObject, methods } = useTable< const { register, tableObject, methods } = useTable<TableData>({
{
total: number
list: TableData[]
},
TableData
>({
getListApi: getTableListApi, getListApi: getTableListApi,
delListApi: delTableListApi, delListApi: delTableListApi,
response: { response: {
@ -196,9 +190,7 @@ const save = async () => {
if (isValid) { if (isValid) {
loading.value = true loading.value = true
const data = (await write?.getFormData()) as TableData const data = (await write?.getFormData()) as TableData
const res = await saveTableApi({ const res = await saveTableApi(data)
data
})
.catch(() => {}) .catch(() => {})
.finally(() => { .finally(() => {
loading.value = false loading.value = false

View File

@ -3,7 +3,9 @@ import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm' import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue' import { PropType, reactive, watch } from 'vue'
import { TableData } from '@/api/table/types' import { TableData } from '@/api/table/types'
import { required } from '@/utils/formRules' import { useValidator } from '@/hooks/web/useValidator'
const { required } = useValidator()
const props = defineProps({ const props = defineProps({
currentRow: { currentRow: {
@ -17,12 +19,12 @@ const props = defineProps({
}) })
const rules = reactive({ const rules = reactive({
title: [required], title: [required()],
author: [required], author: [required()],
importance: [required], importance: [required()],
pageviews: [required], pageviews: [required()],
display_time: [required], display_time: [required()],
content: [required] content: [required()]
}) })
const { register, methods, elFormRef } = useForm({ const { register, methods, elFormRef } = useForm({

View File

@ -25,9 +25,7 @@ const save = async () => {
if (isValid) { if (isValid) {
loading.value = true loading.value = true
const data = (await write?.getFormData()) as TableData const data = (await write?.getFormData()) as TableData
const res = await saveTableApi({ const res = await saveTableApi(data)
data
})
.catch(() => {}) .catch(() => {})
.finally(() => { .finally(() => {
loading.value = false loading.value = false

View File

@ -16,11 +16,7 @@ const { t } = useI18n()
const currentRow = ref<Nullable<TableData>>(null) const currentRow = ref<Nullable<TableData>>(null)
const getTableDet = async () => { const getTableDet = async () => {
const res = await getTableDetApi({ const res = await getTableDetApi(query.id as string)
params: {
id: query.id as string
}
})
if (res) { if (res) {
currentRow.value = res.data currentRow.value = res.data
} }

View File

@ -20,11 +20,7 @@ const { t } = useI18n()
const currentRow = ref<Nullable<TableData>>(null) const currentRow = ref<Nullable<TableData>>(null)
const getTableDet = async () => { const getTableDet = async () => {
const res = await getTableDetApi({ const res = await getTableDetApi(query.id as string)
params: {
id: query.id as string
}
})
if (res) { if (res) {
currentRow.value = res.data currentRow.value = res.data
} }
@ -42,9 +38,7 @@ const save = async () => {
if (validate) { if (validate) {
loading.value = true loading.value = true
const data = (await write?.getFormData()) as TableData const data = (await write?.getFormData()) as TableData
const res = await saveTableApi({ const res = await saveTableApi(data)
data
})
.catch(() => {}) .catch(() => {})
.finally(() => { .finally(() => {
loading.value = false loading.value = false

View File

@ -18,13 +18,7 @@ defineOptions({
const { push } = useRouter() const { push } = useRouter()
const { register, tableObject, methods } = useTable< const { register, tableObject, methods } = useTable<TableData>({
{
total: number
list: TableData[]
},
TableData
>({
getListApi: getTableListApi, getListApi: getTableListApi,
delListApi: delTableListApi, delListApi: delTableListApi,
response: { response: {

View File

@ -4,9 +4,11 @@ import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue' import { PropType, reactive, watch } from 'vue'
import { TableData } from '@/api/table/types' import { TableData } from '@/api/table/types'
import { useI18n } from '@/hooks/web/useI18n' import { useI18n } from '@/hooks/web/useI18n'
import { required } from '@/utils/formRules' import { useValidator } from '@/hooks/web/useValidator'
import { IDomEditor } from '@wangeditor/editor' import { IDomEditor } from '@wangeditor/editor'
const { required } = useValidator()
const props = defineProps({ const props = defineProps({
currentRow: { currentRow: {
type: Object as PropType<Nullable<TableData>>, type: Object as PropType<Nullable<TableData>>,
@ -22,7 +24,7 @@ const schema = reactive<FormSchema[]>([
label: t('exampleDemo.title'), label: t('exampleDemo.title'),
component: 'Input', component: 'Input',
formItemProps: { formItemProps: {
rules: [required] rules: [required()]
}, },
colProps: { colProps: {
span: 24 span: 24
@ -33,7 +35,7 @@ const schema = reactive<FormSchema[]>([
label: t('exampleDemo.author'), label: t('exampleDemo.author'),
component: 'Input', component: 'Input',
formItemProps: { formItemProps: {
rules: [required] rules: [required()]
} }
}, },
{ {
@ -45,7 +47,7 @@ const schema = reactive<FormSchema[]>([
valueFormat: 'YYYY-MM-DD HH:mm:ss' valueFormat: 'YYYY-MM-DD HH:mm:ss'
}, },
formItemProps: { formItemProps: {
rules: [required] rules: [required()]
} }
}, },
{ {
@ -53,7 +55,7 @@ const schema = reactive<FormSchema[]>([
label: t('exampleDemo.importance'), label: t('exampleDemo.importance'),
component: 'Select', component: 'Select',
formItemProps: { formItemProps: {
rules: [required] rules: [required()]
}, },
componentProps: { componentProps: {
options: [ options: [
@ -78,7 +80,7 @@ const schema = reactive<FormSchema[]>([
component: 'InputNumber', component: 'InputNumber',
value: 0, value: 0,
formItemProps: { formItemProps: {
rules: [required] rules: [required()]
} }
}, },
{ {
@ -101,12 +103,12 @@ const schema = reactive<FormSchema[]>([
]) ])
const rules = reactive({ const rules = reactive({
title: [required], title: [required()],
author: [required], author: [required()],
importance: [required], importance: [required()],
pageviews: [required], pageviews: [required()],
display_time: [required], display_time: [required()],
content: [required] content: [required()]
}) })
const { register, methods, elFormRef } = useForm({ const { register, methods, elFormRef } = useForm({

View File

@ -3,7 +3,6 @@ import { reactive, ref, unref, watch } from 'vue'
import { Form } from '@/components/Form' import { Form } from '@/components/Form'
import { useI18n } from '@/hooks/web/useI18n' import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElCheckbox, ElLink } from 'element-plus' import { ElButton, ElCheckbox, ElLink } from 'element-plus'
import { required } from '@/utils/formRules'
import { useForm } from '@/hooks/web/useForm' import { useForm } from '@/hooks/web/useForm'
import { loginApi, getTestRoleApi, getAdminRoleApi } from '@/api/login' import { loginApi, getTestRoleApi, getAdminRoleApi } from '@/api/login'
import { useCache } from '@/hooks/web/useCache' import { useCache } from '@/hooks/web/useCache'
@ -11,9 +10,10 @@ import { useAppStore } from '@/store/modules/app'
import { usePermissionStore } from '@/store/modules/permission' import { usePermissionStore } from '@/store/modules/permission'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import type { RouteLocationNormalizedLoaded, RouteRecordRaw } from 'vue-router' import type { RouteLocationNormalizedLoaded, RouteRecordRaw } from 'vue-router'
import { IUserModel } from '@/api-types/user' import { UserType } from '@/api/login/types'
import md5 from 'js-md5' import { useValidator } from '@/hooks/web/useValidator'
import { cloneDeep } from 'lodash-es'
const { required } = useValidator()
const emit = defineEmits(['to-register']) const emit = defineEmits(['to-register'])
@ -28,8 +28,8 @@ const { wsCache } = useCache()
const { t } = useI18n() const { t } = useI18n()
const rules = { const rules = {
user_name: [required], username: [required()],
password: [required] password: [required()]
} }
const schema = reactive<FormSchema[]>([ const schema = reactive<FormSchema[]>([
@ -40,7 +40,7 @@ const schema = reactive<FormSchema[]>([
} }
}, },
{ {
field: 'user_name', field: 'username',
label: t('login.username'), label: t('login.username'),
value: 'admin', value: 'admin',
component: 'Input', component: 'Input',
@ -123,17 +123,13 @@ const signIn = async () => {
if (isValid) { if (isValid) {
loading.value = true loading.value = true
const { getFormData } = methods const { getFormData } = methods
const formData = await getFormData<IUserModel>() const formData = await getFormData<UserType>()
try { try {
const { result } = await loginApi( const res = await loginApi(formData)
Object.assign(cloneDeep(formData), {
password: md5(formData.password)
})
)
if (result) { if (res) {
wsCache.set(appStore.getUserInfo, result) wsCache.set(appStore.getUserInfo, res.data)
getRole() getRole()
} }
} finally { } finally {
@ -146,22 +142,20 @@ const signIn = async () => {
// //
const getRole = async () => { const getRole = async () => {
const { getFormData } = methods const { getFormData } = methods
const formData = await getFormData<IUserModel>() const formData = await getFormData<UserType>()
const params = { const params = {
roleName: formData.user_name roleName: formData.username
} }
// admin - // admin -
// test - // test -
const res = const res =
formData.user_name === 'admin' formData.username === 'admin' ? await getAdminRoleApi(params) : await getTestRoleApi(params)
? await getAdminRoleApi({ params })
: await getTestRoleApi({ params })
if (res) { if (res) {
const { wsCache } = useCache() const { wsCache } = useCache()
const routers = res.data.list || [] const routers = res.data || []
wsCache.set('roleRouters', routers) wsCache.set('roleRouters', routers)
formData.user_name === 'admin' formData.username === 'admin'
? await permissionStore.generateRoutes('admin', routers).catch(() => {}) ? await permissionStore.generateRoutes('admin', routers).catch(() => {})
: await permissionStore.generateRoutes('test', routers).catch(() => {}) : await permissionStore.generateRoutes('test', routers).catch(() => {})

View File

@ -3,22 +3,16 @@ import { Form } from '@/components/Form'
import { reactive, ref, unref } from 'vue' import { reactive, ref, unref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n' import { useI18n } from '@/hooks/web/useI18n'
import { useForm } from '@/hooks/web/useForm' import { useForm } from '@/hooks/web/useForm'
import { ElButton, ElInput, FormRules, ElMessage } from 'element-plus' import { ElButton, ElInput, FormRules } from 'element-plus'
import { getCodeApi, registerApi } from '@/api/register'
import { useValidator } from '@/hooks/web/useValidator' import { useValidator } from '@/hooks/web/useValidator'
import { IUserModel } from '@/api-types/user'
import md5 from 'js-md5'
import { cloneDeep } from 'lodash-es'
const emit = defineEmits(['to-login']) const emit = defineEmits(['to-login'])
const { register, methods, elFormRef } = useForm() const { register, elFormRef } = useForm()
const { getFormData } = methods
const { t } = useI18n() const { t } = useI18n()
const { required, lengthRange, notSpace, notSpecialCharacters, isEqual } = useValidator() const { required } = useValidator()
const schema = reactive<FormSchema[]>([ const schema = reactive<FormSchema[]>([
{ {
@ -28,7 +22,7 @@ const schema = reactive<FormSchema[]>([
} }
}, },
{ {
field: 'user_name', field: 'username',
label: t('login.username'), label: t('login.username'),
value: '', value: '',
component: 'Input', component: 'Input',
@ -87,62 +81,16 @@ const schema = reactive<FormSchema[]>([
]) ])
const rules: FormRules = { const rules: FormRules = {
user_name: [ username: [required()],
required('用户名不能为空'), password: [required()],
{ check_password: [required()],
validator: (_, value, callback) => code: [required()]
lengthRange(value, callback, { min: 2, max: 10, message: '用户名长度必须在2-10之间' })
},
{
validator: (_, value, callback) => notSpace(value, callback, '用户名不能有空格')
}
],
password: [
required('密码不能为空'),
{
validator: (_, value, callback) =>
lengthRange(value, callback, { min: 5, max: 20, message: '密码长度必须在5-20之间' })
},
{
validator: (_, value, callback) => notSpecialCharacters(value, callback, '密码不能是特殊字符')
}
],
check_password: [
required('确认密码不能为空'),
{
validator: (_, value, callback) =>
lengthRange(value, callback, { min: 5, max: 20, message: '确认密码长度必须在5-20之间' })
},
{
validator: (_, value, callback) =>
notSpecialCharacters(value, callback, '确认密码不能是特殊字符')
},
{
validator: async (_, value, callback) => {
const formData = await getFormData<Omit<IUserModel, 'is_admin'>>()
return isEqual(value, formData.password, callback, '两次密码不一致')
}
}
],
code: [required('验证码不能为空')]
} }
const toLogin = () => { const toLogin = () => {
emit('to-login') emit('to-login')
} }
const codeUrl = ref('')
const codeUuid = ref('')
const getCode = async () => {
const { result } = await getCodeApi()
if (result) {
const { url, uuid } = result
codeUrl.value = url
codeUuid.value = uuid
}
}
getCode()
const loading = ref(false) const loading = ref(false)
const loginRegister = async () => { const loginRegister = async () => {
@ -151,18 +99,7 @@ const loginRegister = async () => {
if (valid) { if (valid) {
try { try {
loading.value = true loading.value = true
const formData = await getFormData<Omit<IUserModel, 'is_admin'>>() toLogin()
const { result } = await registerApi(
Object.assign(cloneDeep(formData), {
uuid: codeUuid.value,
password: md5(formData.password),
check_password: md5(formData.check_password)
})
)
if (result) {
ElMessage.success('注册成功')
toLogin()
}
} finally { } finally {
loading.value = false loading.value = false
} }
@ -187,12 +124,7 @@ const loginRegister = async () => {
<template #code="form"> <template #code="form">
<div class="w-[100%] flex"> <div class="w-[100%] flex">
<ElInput <ElInput v-model="form['code']" :placeholder="t('login.codePlaceholder')" />
v-model="form['code']"
:placeholder="t('login.codePlaceholder')"
class="!w-[calc(100%-150px)]"
/>
<div v-html="codeUrl" class="h-38px cursor-pointer w-150px" @click="getCode"></div>
</div> </div>
</template> </template>

4
types/global.d.ts vendored
View File

@ -25,7 +25,7 @@ declare type AxiosMethod = 'get' | 'post' | 'delete' | 'put'
declare type AxiosResponseType = 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream' declare type AxiosResponseType = 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream'
declare type AxiosConfig = { declare interface AxiosConfig {
params?: any params?: any
data?: any data?: any
url?: string url?: string
@ -36,5 +36,5 @@ declare type AxiosConfig = {
declare interface IResponse<T = any> { declare interface IResponse<T = any> {
code: string code: string
result: T extends any ? T : T & any data: T extends any ? T : T & any
} }