简体   繁体   中英

Push an object to an array vue.js

I am getting data from excel and trying to save that data into an array. 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') . 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).

Change your function into 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 () => {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM