Currently, I am working on enhancing my skills in Vue.js and have encountered an issue with sorting arrays in Vue.js. Despite using the sort(a-b) method for ascending order (least alphabet/value first), the array remains unchanged. Even with a function inside the computed property, I can't seem to make it work after hours of trying. Below is the code snippet:
<template>
<div>
<Navbar/>
<div class="container p-4">
<h1>{{ title }}</h1><br />
<br>
<Button/>
<Table :people="sortedPeople"/>
</div>
<Modal @submit="submitPerson" />
</div>
</template>
<script>
import Navbar from './components/Navbar.vue'
import Button from './components/Button'
import Table from './components/Table.vue'
import Modal from './components/Modal.vue'
export default {
name: 'App',
data(){
return {
title: 'People',
name:'Rename This',
people: [
{
fname: 'Ab',
lname: 'Zigzag'
},
{
fname: 'Al',
lname: 'Alabasta'
}
],
}
},
components: { Button, Navbar, Table, Modal },
computed:{
sortedPeople(){
return this.people.sort((a, b) => a.lname - b.lname)
}
},
methods: {
submitPerson(person) {
if(person.first_name && person.last_name) {
this.people.push({ fname: person.first_name, lname: person.last_name })
}
}
}
}
</script>
Please find below the code snippet for my table component:
<template>
<table class="table table-sm table-responsive table-hover">
<thead>
<tr>
<th>Number</th>
<th>Names</th>
<th>Score</th>
</tr>
</thead>
<tbody v-for="(person, i) in people">
<tr>
<td>{{ i+=1 }}</td>
<td>{{ person.fname+" "+person.lname }}</td>
<td>{{ Math.floor(Math.random() * 100) }}/100</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
name: "Table",
props: { people: Array },
}
</script>
I would appreciate any guidance on the correct way to utilize a computed property. Thank you in advance.