<template>
<view class="userInfo-contanier">
<view class="userInfo-detail" @click="chooseImage">
<text>头像</text>
<view>
<image :src="userInfo.avatar"></image>
<text>></text>
</view>
</view>
</view>
</template>
import {
getCurrentInstance
} from "vue";
const {
proxy
} = getCurrentInstance();
let token = uni.getStorageSync('token');
选择头像
// 选择头像
function chooseImage() {
uni.chooseImage({
count: 1, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: function(res) {
//获取选择上传图片的路径
console.log(JSON.stringify(res.tempFilePaths));
//执行上传图片这个方法
sendImage(res.tempFilePaths)
}
});
}
上传头像
// 上传头像
function sendImage(option) {
uni.showLoading({
title: '上传中'
});
uni.uploadFile({
url: "api",//上传头像的请求地址
filePath: option[0],//上传图片的路径
name: 'file',
formData: {
token
},
success: (res) => {
console.log(res);
let update = JSON.parse(res.data);//获取上传成功后的数据(注意转为json格式)
console.log(update);
proxy.$http({
url: 'api',//修改头像的请求地址
method: 'get',
data: {
avatar: update.data.fullurl//上传成功后的图片路径(注意前面要转成json格式,否则会找不到)
}
}).then(res => {
//修改成功后的操作
uni.hideLoading()
})
}
});
}
注:proxy.$http({})是自己对请求进行了简易的封装,如果需要,请跳转至链接: uniapp+vue3,对请求的简单封装配置以及使用
完整代码
<template>
<view class="userInfo-contanier">
<view class="userInfo-detail" @click="chooseImage">
<text>头像</text>
<view>
<image :src="userInfo.avatar"></image>
<text>></text>
</view>
</view>
</view>
</template>
<script>
import {
ref,
reactive,
onMounted,
getCurrentInstance
} from "vue";
export default {
setup() {
let userInfo = ref(uni.getStorageSync('userInfo'));
let token = uni.getStorageSync('token');
const {
proxy
} = getCurrentInstance();
onMounted(() => {
console.log(userInfo.value)
});
// 选择头像
function chooseImage() {
uni.chooseImage({
count: 1, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: function(res) {
console.log(JSON.stringify(res.tempFilePaths));
sendImage(res.tempFilePaths)
}
});
}
// 上传头像
function sendImage(option) {
uni.showLoading({
title: '上传中'
});
uni.uploadFile({
url: "api",//上传头像的请求地址
filePath: option[0],
name: 'file',
formData: {
token
},
success: (res) => {
console.log(res);
let update = JSON.parse(res.data);
console.log(update);
proxy.$http({
url: 'api',//修改头像的请求地址
method: 'get',
data: {
avatar: update.data.fullurl
}
}).then(res => {
uni.showToast({
title: res.data.msg,
duration: 2000,
icon: "none"
});
if (res.data.code == 1) {
uni.setStorageSync("userInfo", res.data.data);
}
uni.hideLoading()
})
}
});
}
return {
userInfo,
chooseImage
}
}
}
</script>
<style lang="scss" scoped>
.userInfo-detail {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1rpx solid #f2f2f2;
padding: 30rpx;
color: gray;
view {
display: flex;
align-items: center;
text {
margin-left: 20rpx;
}
image {
width: 100rpx;
height: 100rpx;
border-radius: 50rpx;
}
}
}
</style>