1.提要信息
1.1 catch和then方法
then
和catch
是JavaScript中Promise对象的两个方法,用于处理异步操作的成功(成功回调)和失败(失败回调)情况。这两个方法通常与async/await
语法一起使用,但也可以单独使用。
(1) then 方法
then
方法是Promise实例链式调用的一部分,它接收一个或多个函数作为参数。
这些函数会在Promise成功解决(fulfilled)后被调用。如果Promise成功解决,then
方法的第一个参数(如果有的话)会被调用,并且它的返回值会传递给下一个then
方法,或者被catch
方法捕获(如果没有更多的then
方法)。
promise.then(onFulfilled, onRejected);
onFulfilled
:当Promise成功解决时调用的函数。onRejected
:当Promise被拒绝时调用的函数(可选)。
(2) catch 方法
catch
方法是Promise实例链式调用的一部分,它接收一个函数作为参数。
这个函数会在Promise被拒绝(rejected)后被调用。catch
方法返回一个新的Promise,这个新的Promise会在捕获到错误后解决。
promise.catch(onRejected);
onRejected
:当Promise被拒绝时调用的函数。
2.退出登录
2.1 代码处理
这段处理了用户在界面上执行的命令:如果是退出登录,则清除token和用户信息,并跳转到登录页面;如果不是退出登录,则跳转到用户页面。
<script setup>
import ...
import { ElMessage, ElMessageBox } from "element-plus";//确认框&提示框
// import { useTokenStore } from "@/stores/token";
// import useUserInfoStore from "@/stores/userInfo";
const tokenStore = useTokenStore()
// const userInfoStore = useUserInfoStore()
import { useRouter } from "vue-router";
const router = useRouter()
const handleCommand = (command)=>{//在浏览器控制台中,输出command数据// console.log(command) 👈测试函数if (command === 'logout'){ElMessageBox.confirm('退?','提示',{confirmButtonText:'确认',cancelButtonText:'取消',type:'warning'}).then(async()=>{// console.log('点击了确认') 👈测试函数//退出登录//清除状态管理Pinia中存放的数据tokenStore.removeToken()userInfoStore.removeInfo()//跳转至登录界面router.push('/login')ElMessage({type:'success',message:'用户退啦!'})}).catch(()=>{ElMessage({type:'info',message:'用户取消了退出'})})}else{router.push('/user/'+command)}
}
</script>
2.2 效果视图
3.用户基本资料界面
3.1 修改信息函数代码
文件地址:src\views\user\UserInfo.vue
允许用户修改他们的昵称和邮箱信息,并通过表单验证确保输入符合要求。
如果输入验证通过,用户点击提交按钮后,会调用updateUserInfo
函数将信息提交到后端,并在成功后更新用户信息。
<script setup>
import { ref } from 'vue';
import useUserInfoStore from '@/stores/userInfo';
const userInfoStore = useUserInfoStore()
const userInfo = ref({ ...userInfoStore.info })
//数据校验
const rules = {nickname: [{required: true, message: "用户请输入用户昵称", trigger: 'blur'}, {pattern: /^\S{2,10}$/,message: '昵称必须是2-10位的非空字符',trigger: 'blur'}],email: [{required: true, message: "请输入用户邮箱", trigger: 'blur'}, {type:'email',message: '邮箱格式不正确',trigger: 'blur'}]
}
//修改个人信息
import { userInfoUpdateService } from '@/apis/user.js'
import { ElMessage } from 'element-plus';
const updateUserInfo = async()=>{let result = await userInfoUpdateService(userInfo.value)ElMessage.success(result.msg?result.msg:'修改成功')userInfoStore.setInfo(userInfo.value)//更新pinia中存放用户信息的数据
}
</script>
<template><el-card class="page-container"><template #header><div class="header"><span>基本资料</span></div></template><el-row><el-col :span="12"><el-form :model="userInfo" :rules = "rules" label-width="100px" size="large"><el-form-item label="登录名称"><el-input v-model="userInfo.username" disabled /></el-form-item><el-form-item label="用户昵称" prop="nickname"><el-input v-model="userInfo.nickname" /></el-form-item><el-form-item label="用户邮箱" prop="email"><el-input v-model="userInfo.email" /></el-form-item><el-form-item><el-button type="primary" @click="updateUserInfo">提交修改</el-button></el-form-item></el-form></el-col></el-row></el-card>
</template>
3.2 暴露地址
文件地址:src\apis\user.js
export const userInfoUpdateService = (userInfoData) => {return request.put('/user/update', userInfoData)
}
3.3 效果视图
4. 更换头像界面
4.1 更换头像函数代码
文件地址:src\views\user\UserAvatar.vue
<script setup>
import {Plus,Upload
} from "@element-plus/icons-vue"import avatar from '@/assets/default.png'
import { ref } from "vue";
import { userAvatarUpdateService, userInfoService } from "@/apis/user.js";
import useUserInfoStore from "@/stores/userInfo";
import { useTokenStore } from "@/stores/token";
const tokenStore = useTokenStore()
const userInfoStore = useUserInfoStore()
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter()
const imgUrl = ref(userInfoStore.info.userPic)const uploadRef = ref()
//上传成功回调函数
const uploadSuccess = (result)=>{imgUrl.value = result.data
}
//修改头像
const updateAvatar = async()=>{let result = await userAvatarUpdateService(imgUrl.value)ElMessage.success(result.msg?result.msg:'修改成功')//同步修改pinia中的头像userInfoStore.info.userPic = imgUrl.value
}
</script><template><el-card class="page-container"><template #header><div class="header"><span>更换头像</span></div></template><el-row><el-col :span="12"><el-upload ref="uploadRef"class="avatar-uploader" :show-file-list="false" :auto-upload="true" action="/apis/upload" name="file" :header="{'Authorization':tokenStore.token}":on-success="uploadSuccess"><img v-if="imgUrl" :src="imgUrl" class="avatar"><img v-else :src="avatar" width="300"/></el-upload><br><el-button size="large" :icon="Plus" @click="uploadRef.$el.querySelector('input').click()">选择图片</el-button><el-button size="large" :icon="Upload" @click="updateAvatar">上传头像</el-button></el-col></el-row></el-card>
</template>
4.2 暴露地址
文件地址:src\apis\user.js
export const userAvatarUpdateService = (avatarURL) => {const params = new URLSearchParams()params.append('avatarURL', avatarURL)return request.patch('/user/updateavatar', params)
}
4.3 效果视图
5. 重置密码界面
5.1 重置密码函数代码
文件地址:src\views\user\UserPassword.vue
<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { userPsdUpdateService } from '@/apis/user';
import { useRouter } from 'vue-router';
const router = useRouter();
const passwordForm = ref(null);
const passwordData = ref({old_Pwd: '',new_Pwd: '',re_Pwd: ''
});const checkRepassword = (rule, value, callback) => {if (value !== passwordData.value.new_Pwd) {callback(new Error('两次输入密码不一致'));} else {callback();}
};const rules = {old_Pwd: [{ required: true, message: '请输入原密码', trigger: 'blur' }],new_Pwd: [{ required: true, message: '请输入新密码', trigger: 'blur' },{ min: 6, message: '密码长度不能小于6位', trigger: 'blur' }],re_Pwd: [{ required: true, message: '请确认新密码', trigger: 'blur' },{ validator: checkRepassword, trigger: 'blur' }]
};const submitPassword = async () => {if (!passwordForm.value) return;passwordForm.value.validate(async (valid) => {if (valid) {try {let result = await userPsdUpdateService(passwordData.value);ElMessage.success(result.msg ? result.msg : '重置密码成功');router.push("/login");} catch (error) {ElMessage.error('重置密码失败');}} else {ElMessage.error('表单校验失败');}});
};
</script><template><el-card class="page-container"><template #header><div class="header"><span>更改密码</span></div></template><el-row><el-col :span="12"><el-form :model="passwordData" :rules="rules" ref="passwordForm"><el-form-item label="原密码" prop="old_Pwd"><el-input type="password" v-model="passwordData.old_Pwd"></el-input></el-form-item><el-form-item label="新密码" prop="new_Pwd"><el-input type="password" v-model="passwordData.new_Pwd"></el-input></el-form-item><el-form-item label="确认新密码" prop="re_Pwd"><el-input type="password" v-model="passwordData.re_Pwd"></el-input></el-form-item><el-form-item><el-button type="primary" @click="submitPassword">修改密码</el-button></el-form-item></el-form></el-col></el-row></el-card>
</template>
5.2 暴露地址
文件地址:src\apis\user.js
export const userPsdUpdateService = (userPsdData) => {return request.post('/user/updatePwd', userPsdData);};
//
//export const userPsdUpdateService = (userPsdData) => {
// const params = new URLSearchParams()
// for (let key in userPsdData) {
// params.append(key, userPsdData[key])
// }
// // return request.post('/user/updatePwd',params)
// return request.post('/user/updatePwd', userPsdData, {
// headers: {
// 'Content-Type': 'application/json'
// }
// });
//}