«this.grades.pu sh не является функцией» При попытке добавить оценку в массив - PullRequest
0 голосов
/ 22 апреля 2020

Привет, я создаю веб-приложение, в котором я могу перечислить свои оценки и получить среднее значение, но я не могу добавить какие-либо оценки в свой массив с помощью кнопки. Когда я нажимаю кнопку «Добавить», я получаю сообщение об ошибке:

TypeError: this.grades.push is not a function

at VueComponent.addGrade (Calculator.vue?1876:54)

at click (eval at ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-

Я также пытаюсь сохранить оценки в локальном хранилище. Что я делаю не так?

Я делаю все с Vue. js и js. Вот код:

<template>
  <div>
    <h2>Grade-Calculator</h2>
    <div>
      <ul>
        <li v-for="(g,idx) in grades" :key="idx">
          {{idx+1}}. Grade : {{g}}
          <button v-on:click="delGrade()">Delete</button>
        </li>
      </ul>
      <div>
        <label>New Grade:</label>
        <input type="text" v-model="newGrade" />
        <button v-on:click="addGrade()">Add</button>
      </div>
      <br />
      <div>
        <p>Average: {{ calcAvg() | round}}</p>
      </div>
    </div>
  </div>
</template>
<!-- The Script-->
<script>
export default {
  data: () => ({
    grades: [],
    newGrade: 0,
    avg: 0,
    formattedNumber: ""
  }),
  name: "Home",
  props: {},

  methods: {
    calcAvg: function() {
      let sum = 0;
      for (var i = 0; i < this.grades.length; i++) {
        let num = parseInt(this.grades[i]);
        sum = sum + num;
      }
      console.log(sum);
      console.log(this.grades.length);
      return sum / this.grades.length;
    },
    addGrade: function() {
      if (this.grades == null) {
        this.grades = [];
      }
      this.grades.push(this.newGrade);
      this.newGrade = 0;
      localStorage.setItem("grades", this.grades);
    },
    delGrade: function() {
      var idx = this.grades.indexOf(this.grades);
      this.grades.splice(idx);
      localStorage.removeItem("grades");
      localStorage.setItem("grades", this.grades);
    }
  },
  mounted() {
    this.grades = localStorage.getItem("grades");
  },
  filters: {
    round: function(value) {
      value = parseFloat(value).toFixed(2);
      //this.formattedNumber = this.avg.toFixed(2);
      return value;
    }
  }
};
</script>

1 Ответ

2 голосов
/ 22 апреля 2020

Веб-хранилище хранит строки , поэтому проблема в mounted:

this.grades = localStorage.getItem("grades");

Теперь this.grades - это строка, в которой нет push method.

Сохраните ваш массив как JSON:

localStorage.setItem("grades", JSON.stringify(this.grades));

и проанализируйте его при извлечении:

this.grades = JSON.parse(localStorage.getItem("grades")) || [];

Часть || [] дает пустой массив если элемент не находится в хранилище (getItem возвращает null, который преобразуется в "null", а затем анализируется JSON.parse обратно в null, что ложно).

...