We have a list of objects. We can sort the list using the array sort function.
Depending on which button is clicked, we either sort ascending or descending.
This is the App.vue file:
<template>
<div>
<button @click="sort(1)">Ascending</button>
<button @click="sort(-1)">Descending</button>
<h2 v-for="v in arr">{{v.id}} - {{v.val}}</h2>
</div>
</template>
<script>
export default {
data() {
return {
arr: [
{id: "A", val: 5},
{id: "B", val: 7},
{id: "C", val: 9},
{id: "D", val: 12},
{id: "E", val: 15},
{id: "F", val: 6}
]
}
},
methods: {
sort: function(p) {
this.arr.sort(function(a,b) {
return (a.val - b.val) * p;
});
}
}
}
</script>
<style>
button {
color: white;
background-color: green;
border-radius: 10px;
padding: 5px;
display: block;
margin: 0 auto;
}
h2 {
color: blue;
background-color: orange;
width: 400px;
}
</style>
This is the output after ascending button is clicked:
No comments:
Post a Comment