实现Element的upload组件的图片本地预览
upload组件的html代码如下:
<el-upload
class="avatar-uploader"
action=""
:show-file-list="false"
:before-upload="beforeAvatarUpload"
v-model="ruleForm.coverFile"
>
<img
v-if="ruleForm.coverUrl"
:src="ruleForm.coverUrl"
class="avatar"
/>
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
在vue组件中的js代码如下:
return {
ruleForm: {
coverUrl: "",
coverFile: ""
},
methods: {
beforeAvatarUpload(file) {
const isJPG = file.type === "image/jpeg";
const isPNG = file.type === "image/png";
const isLt1M = file.size / 1024 / 1024 < 1;
if (!isJPG && !isPNG) {
this.$message.error("上传头像图片只能是 JPG 或 PNG 格式!");