I am having an issue whereby my results do not display when the page loads. It will only display if i make a selection on the drop-down menu.
I have tried adding the function to the mounted property but that doesn't seem to work. Any ideas what this might be?
<select v-model="sortResults"
@change="sortalphabetically"
aria-label="sortby"
id="sortby">
<option disabled value="" selected>Select</option>
<option value="alpha">Alphabetically</option>
<option value="relevance">Relevance</option>
</select>
methods: {
sortalphabetically() {
switch (this.sortResults) {
case "alpha":
this.theResults = [...this.results].sort((a, b) =>
a.metaData.title > b.metaData.title ? 1 : -1
);
break;
case "relevance":
this.theResults = [...this.results];
break;
}
},
}
data: function () {
return {
sortResults: "relevance"
}
import Result from "@/components/Result.vue";
mounted() {
this.dataFilters;
this.updateURL();
this.theResults();
},
};
CodePudding user response:
I reproduced your code by adding some changes and it works correctly.
First, you do not sort your values in the second switch's case. It maybe is your business :-) It doesn't matter.
Second, in showing results if you are using v-if
please do not use i
as the index of the result array for its key, It won't work. Vue and even React do not recognise the changing order of an array if its index is being used as the key. So, use the items' unique ids.
<template>
<div>
<select
id="sortby"
aria-label="sortby"
v-model="sortResults"
@change="sortalphabetically"
>
<option disabled value="" selected>Select</option>
<option value="alpha">Alphabetically</option>
<option value="relevance">Relevance</option>
</select>
<div style="background-color: aquamarine">
<div
v-for="item in theResults" :key="item.metaData.id"
>
{{item.metaData.title}}
</div>
</div>
</div>
</template>
<script>
export default {
name: 'BaseSelectTest',
data() {
return {
sortResults: 'relevance',
theResults: [],
results: [
{ metaData: { title: 'BBBB', id: 2 } },
{ metaData: { title: 'DDDD', id: 4 } },
{ metaData: { title: 'AAAA', id: 1 } },
{ metaData: { title: 'CCCC', id: 3 } },
{ metaData: { title: 'EEEE', id: 5 } },
],
};
},
methods: {
sortalphabetically() {
switch (this.sortResults) {
case 'alpha':
this.theResults = [...this.results]
.sort((a, b) => (a.metaData.title > b.metaData.title ? 1 : -1));
break;
case 'relevance':
this.theResults = [...this.results] // You may omit the next line
// .sort((a, b) => (a.metaData.title > b.metaData.title ? -1 : 1));
break;
default:
// nothing left to do
}
},
},
mounted() {
this.sortalphabetically(); // It's optional if you ignore sorting for 'relevance'
},
};
</script>
Finally, if your flaw persists, you need to check out the showing result codes. Of course, it's possible to observe data changes using the Vue Dev Tool for sure.