I'm using Vue cli and I have an array of users that I display as a profile card in template that I would like to sort by name. I'm using Vuex to store data.
In the child component I have in my template:
<div class="outside" v-for="(item, index) in arrays" :key="item.id" v-bind:id="item.name">
<div class="stay"> <p class="n"> {{ item.name }}</p> </div>
and I'm getting the Vuex data:
computed: {
arrays () {
return this.$store.state.arrays
},
}
and my array contains:
arrays: [
{ name: 'Peter'},
{ name: 'Beth'},
{ name: 'Daniel'},
]
I used a function in the child component:
computed:{
sortedArray: function() {
function compare(a, b) {
if (a.name < b.name)
return -1;
if (a.name > b.name)
return 1;
return 0;
}
return this.arrays.sort(compare);
}
},
and changed the template to:
<div class="outside" v-for="(item, index) in sortedArrays" :key="item.id" v-bind:id="item.name">
But I'd like a way to do this onclick (in the parent), instead of always displaying it in order.
In my parent component I have:
<div class="begin">
<div class="b">Sort By:
<select name="sort" class="sort" >
<option value="name" @click="sortArrays()">Name</option>
</select>
</div>
<childComponent></childComponent>
</div>
I would like a sortArrays function I can use in the parent to display the user profile card in alphabetical order when I click on sort by name.
Thanks so much!