Obtengo datos de Excel y trato de guardar esos datos en una matriz. Quiero insertar los objetos en una matriz vacía cuando cargo el archivo de Excel, pero recibo este error Uncaught TypeError: Cannot read properties of undefined (reading 'push') . Aquí está mi código:
<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>La solución es bastante fácil. Su itemsList no está definida, porque this no es lo que espera que sea (el objeto componente).
Cambie su function a Función de flecha () => {} .
// 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); }; Le sugiero que lea sobre el enlace en la function frente a las funciones de flecha () => {}