一、功能需求分析
头像回显:当用户进入修改头像页面时,应立即显示当前已设置的头像。
图片上传:用户能够从本地选择一张图片,并将其上传至服务器。
头像修改:成功上传图片后,用户点击 “上传头像” 按钮,实现头像的最终修改,并更新服务器上的头像信息。
二、实现步骤及代码解析
(一)搭建页面
在 user awater 的 view 中找到资料修改头像部分的代码,将其复制到 vs code 中进行编辑。
页面核心组件为 yellow - upload,用于图片上传,其下方有 “选择图片” 和 “上传图像” 两个按钮。同时,页面定义了数据模型 IMGULL,并绑定到 IMG 标签,初始值为默认图片。
(二)头像回显
导入相关模块
首先导入 pr(假设为存储用户信息的模块),以获取用户头像信息。
import { useUserInfo } from '@/store/userInfo.js';
const userInfoStore = useUserInfo();
获取并设置头像地址
从 pr 中获取用户头像的预览地址,并将其赋值给 IMGULL,使其能正确回显用户头像。
const imgUrl = ref(userInfoStore.info.userPic);
(三)图片上传
- 设置 yellow - upload 属性
outer gun upload:设置为 true,指定自动上传图片。
:outer-gun-upload=“true”
action:指定上传路径为 gua p i gun upload(假设为服务器接收图片上传的接口路径)。
action=“gua p i gun upload”
name:指定上传字段名为 fire。
name=“fire”
hers:携带 token 进行身份验证。先导入 token。
import { useTokenStore } from ‘@/store/guToken.js’;
const tokenStore = useTokenStore(); - 在 hers 中设置请求头携带 token。
:hers=“{ Authorization: tokenStore.token }”
On gun success:指定上传成功后的回调函数 upload success。
:on-gun-success=“uploadSuccess” - 上传成功回调函数
在回调函数中,将获取到的图片 URL 赋值给 IMGULL,以便在页面上显示上传后的图片。
const uploadSuccess = (result) => {
imgUrl.value = result.data;
};
(四)头像修改
- 绑定按钮单击事件
在 “上传头像” 按钮上绑定单击事件 update。
<button @click="update">上传头像</button>
- 提供接口调用函数
根据接口文档,在 user.js 中声明修改头像的函数 user a water update service。
接口请求路径为 /user/update water,请求方式为 patch,参数为 a
water url。
export const userAWaterUpdateService = (waterUrl) => {
const params = new URLSearchParams();
params.append('a water', waterUrl);
return request.patch('/user/update water', params);
};
- 在事件函数中调用接口并处理结果
在 update 函数中调用修改头像接口,并根据接口返回结果进行相应处理。 - 导入修改头像函数和提示组件 message。
import { userAWaterUpdateService } from '@/api/user.js';
import { message } from 'element-plus';
const update = async () => {
const result = await userAWaterUpdateService(imgUrl.value);
if (result.msg) {
message.success(result.msg);
} else {
message.success('修改成功');
}
// 更新pr中的头像地址
userInfoStore.setInfo({ userPic: imgUrl.value });
};
通过以上步骤,我们成功实现了用户头像修改功能,包括头像回显、图片上传和头像修改,并在整个过程中进行了详细的代码编写和功能处理。