vue3图片浏览与上传功能
时间: 2023-07-28 11:31:10 浏览: 48
要实现Vue3的图片浏览与上传功能,你可以按照以下步骤操作:
1. 安装Vue3的图片浏览插件,比如vue-photo-preview,可以通过npm安装。
2. 在Vue3的组件中引入vue-photo-preview插件,并且在组件中定义一个data属性,用来保存需要显示的图片的url。
3. 在组件的template中,使用vue-photo-preview的标签,将data属性中的图片url显示出来。可以通过v-for循环来实现多张图片的显示。
4. 实现图片上传功能,可以使用Vue3的Element-Plus组件库中的el-upload组件。在组件中定义一个uploadUrl属性,用来指定上传图片的接口地址。然后在template中使用el-upload标签,绑定uploadUrl属性,即可实现图片上传功能。
下面是一个简单的示例代码,供参考:
```
<template>
<div>
<div v-for="imageUrl in imageUrls" :key="imageUrl">
<img :src="imageUrl" @click="previewImage(imageUrl)">
</div>
<el-upload
class="upload-demo"
action="/your-upload-api"
:show-file-list="false"
:on-success="handleSuccess"
:before-upload="beforeUpload">
<el-button>点击上传</el-button>
</el-upload>
</div>
</template>
<script>
import VuePhotoPreview from 'vue-photo-preview';
import 'vue-photo-preview/dist/skin.css';
import { ElUpload, ElButton } from 'element-plus';
export default {
components: {
VuePhotoPreview,
ElUpload,
ElButton,
},
data() {
return {
imageUrls: [],
uploadUrl: '/your-upload-api',
};
},
methods: {
previewImage(imageUrl) {
this.$photoPreview.show({
photos: [
{
url: imageUrl,
},
],
});
},
handleSuccess(response) {
if (response.status === 'success') {
this.imageUrls.push(response.imageUrl);
}
},
beforeUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isPNG = file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG && !isPNG) {
this.$message.error('上传图片只能是 JPG/PNG 格式!');
return false;
}
if (!isLt2M) {
this.$message.error('上传图片大小不能超过 2MB!');
return false;
}
return true;
},
},
};
</script>
```