vite+ts——user.ts——ts接口定义+axios请求的写法

js 复制代码
import axios from 'axios';
import qs from 'query-string';
import {UserState} from '@/store/modules/user/types';

export interface LoginData{
	username:string;
	password:string;
	grant_type?:string;
	scope?:string;
	client_id?:string;
	client_secret?:string;
	response_type?:string;
}
export interface LoginRes{
	access_token:string;
}
export function login(data:LoginData){
	const q:LoginData = {
		...data,
	}
	const param = qs.stringify(q);
	return axios.post<LoginRes>('/connect/token',param,{
		headers:{
			'Content-Type':'application/x-www-form-urlencoded',
		},
		baseURL:import.meta.env.VITE_APP_IDS4_BASE_URL,
	})
}
export function logout(){
	return axios.delete<LoginRes>('/sys-auth/oauth/exit');
}
export function GlLogin(){
	const param = qs.stringify({
		grant_type:'client_credentials',
		client_id:'xafasdfa',
		client_secret:'adsfa',
	})
	return axios.post('/bimserver/auth/oauth/token',param,{
		headers:{
			'Content-Type':'application/x-www-form-urlencoded',
			'isNeedToken':'false',
		},
		baseURL:'/gl_api'
	})
}
export function getUserInfo(userName:string){
	return axios.get<UserState>('/cde-collaboration/user/userInfo',{
		params:{
			userName,
		}
	})
}
export interface UserParams{
	ids?:string;
	names?:string;
}
export function getUserList(params:UserParams){
	return axios.get('/cde-collaboration/user/getUsers',{
		params,
	})
}
export function searchUser(
	searchValue:string,
	projectId:string|undefined = undefined
){
	return axios.get('/cde-collaboration/user/search',{
		params:{
			searchValue,projectId
		}
	})
}
export function getSms(phone:string){
	return axios.get<string>('/sys-user/user/sms_captcha',{
		params:{phone}
	})
}
export function setUserPwd(id:string,pwd:string){
	return axios.get<string>('/cde-collaboration/user/active',{
		params:{
			id,pwd
		}
	})
}
export interface PasswordParams{
	captcha:string;
	key:string;
	phone:string;
	pwd:string;
}
export function editPassword(data:PasswordParams){
	return axios.put('/sys-user/user/password',data)
}
export interface PwdParams{
	oldPwd:string;
	newPwd:string;
	enterPwd?:string;
}
export function modifyPassword(data;PwdParams){
	return axios.put('/sys-user/user/pwd',data)
}
export interface PhoneParams{
	phone:string;
	captcha:string;
	key?:string;
}
export function updataPhone(data:PhoneParams){
	return axios.post('/cde-collaboration/user/changePhone',data)
}
export function getPhoneCode(phone:string){
	return axios.get('/sys-user/user/sms_change_phone_captcha',{
		params:{
			phone,
		}
	})
}
export interface EmailParams{
	username?:string;
	id?:string;
	email:string;
}
export function updateEmail(data:EmailParams){
	return axios.post('/cde-collaboration/user/update',data)
}
export function getThird(key:string){
	return axios.get(`/sys-auth/oauth/render_user/${key}`)
}
export function getSocialInfoByToken(token:string){
	return axios.get('/sys-auth/oauth/user_info',{
		headers:{
			Authorization:`bearer ${token}`
		}
	})
}

UserState------@/store/modules/user/types

js 复制代码
const interface RemoteDataCommon {
  createBy?: string;
  createDate?: string;
  updateBy?: string;
  updateDate?: string;
  deleteFlag?: number;
}
export type RoleType = '' | '*' | 'admin' | 'user';
// 0超级管理员 1项目创建员 -1普通成员
export type AdminType = 0 | 1 | -1;

export interface UserState extends RemoteDataCommon {
  userId?: string;
  id?: string;
  username?: string;
  name?: string;
  phone?: string;
  email?: string;
  accountState?: number;
  avatarToken?: string;
  fid?: number;
  admin: AdminType;
  role: RoleType;
  color?: string;
}

login接口的调用

js 复制代码
<template>
	<a-form ref="loginForm" :model="userInfo" class="login-form" layout="vertical" @submit="handleSubmit">
		<a-form-item field="username" :rules="[{required:true,message:$t('login.form.userName.errMsg')}]"
		:validate-trigger="['change','blur']" hide-label
		>
			<a-input v-model="userInfo.username" :placeholder="$t('login.form.userName.placeholder')">
				<template #prefix><icon-user /></template>
			</a-input>
		</a-form-item>
		<a-form-item field="password" :rules="[{required:true,message:$t('login.form.password.errMsg')}]"
		:validate-trigger="['change','blur']"
		hide-label
		>
			<a-input-password v-model="userInfo.password" :placeholder="$t('login.form.password.placeholder')" allow-clear>
				<template #prefix><icon-lock /></template>
			</a-input-password>
		</a-form-item>
		<a-space :size="16" direction="vertical">
			<div class="login-form-password-acitions">
				<a-checkbox checked="rememberPassword" :model=value="loginConfig.rememberPassword" @change="setRememberPassword as any'>
					{{$t('login.form.rememberPassword')}}
				</a-checkbox>
				<a-link @click="changeLogin(LoginMethods.forget)">{{$t('login.form.forgetPassword')}}</a-link>
			</div>
			<a-button type="primary" html-type="submit" long :loading="loading">{{$t('login.form.login')}}</a-button>
		</a-space>
	</a-form>
</template>
js 复制代码
<script setup lang="ts">
import {reactive} from 'vue';
import {useRouter} from 'vue-router';
import {Message} from '@arco-design/web-vue';
import {ValidatedError} from '@arco-design/web-vue/es/form/interface';
import {useI18n} from 'vue-i18n';
import {useUserStore} from '@vueuse/core';
import useLoading from '@/hooks/loading';
import type {LoginData} from '@/api/user';
import pwdEncrypt from '@/utils/encryption/pwd';
import {dotToSlash} from '@/utils/index';
import LoginMethods from '../constant';
const emit = defineEmits(['changeLogin']);
const changeLogin = (method:LoginMethods)=>{
	emit('chageLogin',method);
}
const router = useRouter();
const {t} = useI18n();
const {loading,setLoading} = useLoading();
const userStore = useUserStore();
const loginConfig = useStorage('login-config',{
	rememberPassword:true,
	username:'',
	password:''
})
const userInfo = reactive({
	username:loginConfig.value.username,
	password:loginConfig.value.password
})
const handleSubmit = async({
	errors,
	values,
}:{
	errors:Record<string,ValidatedError>|undefined;
	values:Record<string,any>;
})=>{
	if(loading.value) return;
	if(!errors){
		setLoading(true);
		try{
			const {username,password} = values;
			const data = {
				username,
				password:pwdEncrypt(password),
				grant_type:'password'
			}
			await userStore.login(data as LoginData).then(()=>{
				userStore.glLogin();
			})
			const {redirect,...othersQuery} = router.currentRoute.value.query;
			router.push({
				path;dotToSlash(redirect as string)||'/dashboard',
				query:{
					...othersQuery
				}
			})
			Message.success(t('login.form.login.success'));
			const {rememberPassword} = loginConfig.value;
			loginConfig.value.username = rememberPassword?username:'';
			loginConfig.value.password = rememberPassword?password:'';
		}catch(err:any){
			if(err?.reponse?.status === 400){
				Message.error(err.response.data);
			}else if(typeof err === 'string'){
				Message.error(err);
			}
		}finllay{
			setLoading(false);
		}
	}
}
const setRememberPassword = (value:boolean)=>{
	loginConfig.value.rememberPassword = value;
}
</script>
<script lang="ts">
export default{
	name:'AccountForm'
}
</script>
相关推荐
三巧1 分钟前
纯CSS吃豆人(JS仅控制进度)
javascript·css·html
SummerGao.2 分钟前
【解决】layui layer的提示框,弹出框一闪而过的问题
前端·layui
软件技术NINI18 分钟前
html css js网页制作成品——HTML+CSS+js美甲店网页设计(5页)附源码
javascript·css·html
JAVA学习通21 分钟前
JAVA多线程(8.0)
java·开发语言
Luck_ff081024 分钟前
【Python爬虫详解】第四篇:使用解析库提取网页数据——BeautifuSoup
开发语言·爬虫·python
天天扭码30 分钟前
从数组到对象:JavaScript 遍历语法全解析(ES5 到 ES6 + 超详细指南)
前端·javascript·面试
学渣6765632 分钟前
什么时候使用Python 虚拟环境(venv)而不用conda
开发语言·python·conda
拉不动的猪32 分钟前
前端开发中常见的数据结构优化问题
前端·javascript·面试
街尾杂货店&32 分钟前
css word
前端·css
Мартин.35 分钟前
[Meachines] [Hard] CrimeStoppers LFI+ZIP-Shell+Firefox-Dec+DLINK+rootme-0.5
前端·firefox