el-upload上传图片时Cannot read properties of undefined (reading 'push') 报错该怎么解决代码示例
时间: 2023-10-18 15:20:02 浏览: 54
这个错误可能是因为你在接受上传的文件时没有正确的初始化数组变量,导致在使用数组的 push 方法时出现了 undefined。
下面是一个 el-upload 组件上传图片的示例代码,你可以参考一下:
```html
<template>
<div>
<el-upload
class="avatar-uploader"
action="/upload"
:show-file-list="false"
:on-success="handleSuccess"
:before-upload="beforeUpload"
>
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</div>
</template>
<script>
export default {
data() {
return {
imageUrl: '',
formData: {
file: []
}
};
},
methods: {
beforeUpload(file) {
this.formData.file.push(file);
},
handleSuccess(response) {
this.imageUrl = response.data.url;
}
}
}
</script>
```
上面的代码中,我们在 data 中声明了一个 formData 对象,并在其中初始化了一个名为 file 的数组变量。在 beforeUpload 方法中,我们将上传的文件对象 push 到 file 数组中。这样就可以避免 undefined 的错误了。