注:如果想直接使用关注私信要websocet上传地址,就可以直接复制到自己的项目使用图片上传了
上传成功后,会返回一个图片地址可以根据自身要求去使用。
1.组件完整代码
<template>
<div class="UploadImg">
<!-- 图片放置位置 -->
<TransitionGroup name="list">
<div class="imgList" key="imgList">
<img
:src="item"
alt=""
v-for="(item, index) in fileList"
:key="index"
/>
<!-- 上传中图片 -->
<div
class="loading"
v-loading="loading"
v-if="loading"
key="loading"
></div>
</div>
</TransitionGroup>
<div class="addBtn" @click="chooseImg">
<el-icon size="40"><Plus /></el-icon>
</div>
<!-- 上传文件最重要的东西 accept="image/*"控制只能选择图片-->
<input
v-show="false"
type="file"
ref="fileInput"
:multiple="multiple"
accept="image/*"
@change="changeImgSuccess"
/>
</div>
</template>
<script setup>
import {
ref,
onMounted,
watch,
defineProps,
defineEmits,
onBeforeUnmount,
} from "vue";
import { ElNotification } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
const props = defineProps({
multiple: {
type: Boolean,
default: false,
},
fileListProps: {
type: Array,
default: () => [],
},
max: {
type: Number,
default: 1,
},
});
const fileList = ref([]);
// 图片加载状态
const loading = ref(false);
// 监听弹窗关闭清空图片
watch(
() => props.fileListProps,
(newVal) => {
console.log(111);
newVal.length === 0 ? (fileList.value = []) : (fileList.value = newVal);
loading.value = false;
},
{
immediate: true,
}
);
const emits = defineEmits(["update:fileListProps"]);
// 导入chunk
import { splitBase64IntoChunks } from "@/utils/splitBase64IntoChunks.js";
const fileInput = ref(null);
// 打开图片选择
const chooseImg = () => {
if (loading.value) {
ElNotification({
tit