[英]Push an object to an array vue.js
I am getting data from excel and trying to save that data into an array.我正在从 excel 获取数据并尝试将该数据保存到数组中。 I want to push the objects into an empty array when I upload the excel file, but I am getting this error
Uncaught TypeError: Cannot read properties of undefined (reading 'push')
.我想在上传 excel 文件时将对象推送到一个空数组中,但出现此错误
Uncaught TypeError: Cannot read properties of undefined (reading 'push')
。 Here is my code:这是我的代码:
<template>
<div id="app">
<input
type="file"
name="xlfile"
id="xlf"
v-on:change="displayFile($event)"
/>
<b-table striped hover bordered :items="itemsList"></b-table>
</div>
</template>
<script>
import * as XLSX from "xlsx/xlsx.mjs";
export default {
name: "App",
data() {
return {
itemsList: [],
};
},
methods: {
displayFile(e) {
var files = e.target.files,
f = files[0];
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
var workbook = XLSX.read(data, { type: "binary" });
let sheetName = workbook.SheetNames[0];
let worksheet = workbook.Sheets[sheetName];
let rowObject = XLSX.utils.sheet_to_row_object_array(worksheet);
const finalJsonData = JSON.parse(
JSON.stringify(rowObject, undefined, 4)
);
finalJsonData.map((item) => {
this.itemsList.push(...item);
});
//console.log(typeof finalJsonData);
};
reader.readAsArrayBuffer(f);
},
},
};
</script>
The solution is fairly easy.解决方案相当简单。 Your
itemsList
is undefined, because your this
is not what you expect it to be (the Component Object).您的
itemsList
未定义,因为您的this
不是您期望的(组件对象)。
Change your function
into Arrow function () => {}
.将您的
function
更改为 Arrow function () => {}
。
// reader.onload = function (e) { // delete this line
reader.onload = (e) => { // add this line
var data = e.target.result;
var workbook = XLSX.read(data, { type: "binary" });
let sheetName = workbook.SheetNames[0];
let worksheet = workbook.Sheets[sheetName];
let rowObject = XLSX.utils.sheet_to_row_object_array(worksheet);
const finalJsonData = JSON.parse(
JSON.stringify(rowObject, undefined, 4)
);
finalJsonData.map((item) => {
this.itemsList.push(...item); // now 'this' is your component
});
//console.log(typeof finalJsonData);
};
I suggest you read about binding in function
versus Arrow functions () => {}
我建议您阅读
function
与箭头函数() => {}
中的绑定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.