利用vue3 element-plus写一个美观的添加图片的页面
时间: 2024-02-01 22:15:10 浏览: 23
好的,我可以给你提供一个基本的示例代码,你可以根据自己的需求进行修改和优化。
首先,你需要安装 Vue3 和 Element Plus。可以使用以下命令进行安装:
```
npm install vue@next
npm install element-plus
```
然后,在你的 Vue3 项目中,创建一个组件,名为 `ImageUpload.vue`,代码如下:
```vue
<template>
<div class="image-upload-container">
<el-upload
ref="upload"
class="upload-demo"
action=""
:show-file-list="false"
:on-change="handleChange"
>
<el-button :disabled="uploading">{{ uploading ? '上传中...' : '上传图片' }}</el-button>
</el-upload>
<div v-if="imageUrl" class="image-preview">
<img :src="imageUrl" alt="Preview image" />
</div>
</div>
</template>
<script>
import { ref } from "vue";
export default {
name: "ImageUpload",
setup() {
const imageUrl = ref("");
const uploading = ref(false);
const handleChange = (file) => {
uploading.value = true;
// 这里模拟上传图片的过程
setTimeout(() => {
imageUrl.value = URL.createObjectURL(file.raw);
uploading.value = false;
}, 2000);
};
return {
imageUrl,
uploading,
handleChange,
};
},
};
</script>
<style scoped>
.image-upload-container {
display: flex;
flex-direction: column;
align-items: center;
}
.upload-demo {
margin: 20px 0;
}
.image-preview {
margin-top: 20px;
width: 300px;
height: 300px;
border: 1px solid #ccc;
display: flex;
justify-content: center;
align-items: center;
}
.image-preview img {
max-width: 100%;
max-height: 100%;
}
</style>
```
这个组件包含一个 `el-upload` 组件和一个预览图片的 `div` 元素。当用户选择图片后,`handleChange` 方法会被调用,模拟上传图片的过程,并将上传成功后的图片地址保存在 `imageUrl` 变量中。
最后,在你的页面中使用该组件,代码如下:
```vue
<template>
<div class="page-container">
<image-upload />
</div>
</template>
<script>
import ImageUpload from "@/components/ImageUpload.vue";
export default {
name: "AddImagePage",
components: {
ImageUpload,
},
};
</script>
<style scoped>
.page-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f5f5f5;
}
</style>
```
这个页面只包含一个 `ImageUpload` 组件,并使用了 Element Plus 提供的样式。你可以根据你的需求进行自定义样式。