uniapp vue3 实现上传头像的组件

uniapp yekong

uniapp需要一个上传头像的功能,这里我们把他单独封装为一个组件,然后通过父组件传值给子组件,子组件更新后传值给父组件。

要实现imageSrc从父组件传入,并在上传成功后将新的图片路径返回给父组件,你可以使用Vue的props$emit功能。下面是修改后的代码:

组件代码

<template>
	<view class="upload-container">
		<view class="image-list" v-if="imageSrc">
			<image class="uploadImg" @click="chooseImage" :src="configs.file + imageSrc"></image>
		</view>
		<image class="uploadImg" v-else @click="chooseImage" src="/BecomeAccompanyingDoctor/uploadPic.png"></image>
	</view>
</template>

<script>
	import configs from '@/config/config';
	export default {
		model: {
			prop: 'imageSrc',
			event: 'update:imageSrc'
		},
		props: {
			imageSrc: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				configs: configs
			};
		},
		methods: {
			chooseImage() {
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePaths = res.tempFilePaths;
						tempFilePaths.forEach((path) => {
							this.uploadImage(path);
						});
					}
				});
			},
			uploadImage(filePath) {
				const uploadTask = uni.uploadFile({
					url: configs.baseUrl + '/files/upload/1',
					filePath: filePath,
					name: 'file',
					success: (uploadFileRes) => {
						const newPath = JSON.parse(uploadFileRes.data).data.path;
						this.$emit('update:imageSrc', newPath);
					}
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.uploadImg {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
	}

	.upload-container {
		display: flex;
		flex-direction: column;
	}

	.upload-btn {
		background-color: #007AFF;
		color: white;
		padding: 10px;
		border-radius: 5px;
		text-align: center;
		margin-bottom: 10px;
	}

	.image-list {
		display: flex;
		flex-wrap: wrap;
	}

	.image-item {
		position: relative;
		margin-right: 10px;
	}

	.upload-image {
		width: 100px;
		height: 100px;
		border-radius: 50%;
	}
</style>

使用组件

<userHead v-model:imageSrc="data.pic"></userHead>
喜欢