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

2023-12-14 15:56:00
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

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接口的调用

<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>
<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>

文章来源:https://blog.csdn.net/yehaocheng520/article/details/134921736
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。