I'm making a webapp with a grades calculator where I can Add grades and delete them. They are saved in a Local Storage. When trying to delete a specifig grade it deletes the grade recently added. How can I specifically delete an int in an Array?
<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: null,
avg: 0,
formattedNumber: ""
}),
name: "Home",
props: {},
methods: {
delGrade: function() {
var idx = this.grades.indexOf(this.grades);
this.grades.splice(idx);
localStorage.removeItem("grades");
localStorage.setItem("grades", this.grades);
}
},
mounted() {
this.grades = JSON.parse(localStorage.getItem("grades")) || [];
},
};
</script>
First you need the grade to delete in delGrade(gradeToDelete)
and once you have it (and its index by this.grades.indexOf(gradeToDelete)
) you can work with the index.
Furthermore, I think.splice needs a deleteCount to remove the element at the index. Try changing this.grades.splice(idx);
to this.grades.splice(idx, 1);
I'm assuming your data looks like integers in an array. In which they will be stored like the example below.
let grades = [8, 9, 5, 6, 3];
localStorage.setItem('grades', JSON.stringify(grades));
To remove a single key from the array, first parse it back to an array format and then use the Array.prototype.filter
method create a new array without the grade that you want to remove.
let gradeToRemove = 5;
let storedGrades = JSON.parse(localStorage.getItem('grades'));
let newGrades = storedGrades.filter(grade => grade !== gradeToRemove);
localStorage.setItem('grades', JSON.stringify(newGrades));
You should provide id, which you want to delete from array
<button v-on:click="delGrade(idx)">Delete</button>
then you should receive that id and use it
delGrade: function(idToDelete) {
this.grades.splice(idToDelete, 1);
localStorage.removeItem("grades"); // it is not necessary, coz you will override all key grades in next line
localStorage.setItem("grades", this.grades);
}
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.