el-upload是ElementUI中的一个组件,可以用来实现图片上传功能。下面是一个基本的el-upload的示例代码:
<template>
<el-upload
class="upload-demo"
action="/upload"
:show-file-list="false"
:on-success="handleSuccess"
:before-upload="beforeUpload">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</template>
<script>
export default {
methods: {
handleSuccess(response) {
this.imageUrl = response.url;
},
beforeUpload(file) {
const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
const isLt500KB = file.size / 1024 < 500;
if (!isJPG) {
this.$message.error('上传的图片只能是 JPG/PNG 格式!');
}
if (!isLt500KB) {
this.$message.error('上传的图片大小不能超过 500KB!');
}
return isJPG && isLt500KB;
}
}
};
</script>
上面的代码实现了一个上传图片的功能,点击“点击上传”按钮,可以选择需要上传的图片,然后会执行beforeUpload函数做图片格式和大小的检查,如果通过检查,会上传图片到服务端,上传成功后会自动调用handleSuccess函数处理返回的图片URL。其中,action属性指定了上传的URL,show-file-list属性表示是否显示已上传的图片列表。
如果要实现删除图片的功能,可以通过v-if指令控制上传按钮和已上传的图片的显示和隐藏。删除图片时,只需要清空imageUrl即可。下面是示例代码:
<template>
<div>
<el-upload
class="upload-demo"
action="/upload"
:show-file-list="false"
:on-success="handleSuccess"
:before-upload="beforeUpload"
v-if="!imageUrl">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
<img :src="imageUrl" v-if="imageUrl">
<el-button v-if="imageUrl" size="small" type="danger" @click="handleDelete">删除图片</el-button>
</div>
</template>
<script>
export default {
data() {
return {
imageUrl: ''
};
},
methods: {
handleSuccess(response) {
this.imageUrl = response.url;
},
beforeUpload(file) {
const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
const isLt500KB = file.size / 1024 < 500;
if (!isJPG) {
this.$message.error('上传的图片只能是 JPG/PNG 格式!');
}
if (!isLt500KB) {
this.$message.error('上传的图片大小不能超过 500KB!');
}
return isJPG && isLt500KB;
},
handleDelete() {
this.imageUrl = '';
}
}
};
</script>