I am using Vue3 together with Collect.js. I have an object records that can have n number of items.
On my website, I display these records - one by one. The current record is captured by a variable called current
Users can navigate through the records (previous or next):
<button @click="navigateRecords('previous')" type="button">
Previous
</button>
<button @click="navigateRecords('next')" type="button">
Next Record
</button>
I have a method called navigateRecords as per below code. Please note that I have to append a key to the current record, called completion.
const props = defineProps({
records: {
type: Object,
},
})
const currentRecordIndex = ref(0);
const current = ref({...collect(props.records.first()), completion: ''});
const navigateRecords = (direction) => {
//If user is clicking on "Next"
if (direction === 'next') {
//If we are at the end of the object, return to first record, else get the next.
if (currentRecordIndex.value === collect(props.records).count() - 1) {
currentRecordIndex.value = 0;
} else {
currentRecordIndex.value++;
}
} else {
//If we are at the end of the object, return to first record, else get the previous.
if (currentRecordIndex.value > 0) {
currentRecordIndex.value--;
}else{
currentRecordIndex.value = collect(props.records).count() - 1;
}
}
//Set the current record, to the one navigated to.
let newValue = collect(props.records).slice(currentRecordIndex.value).first();
current.value = {
...newValue,
completion: newValue.completion || ''
}
}
I find the above code very messy, and I was wondering if there is a more elegant way to do this - perhaps even without using collect.js. Either way, I am using Vue3's composition API .
refandcollectconstructs, but at the very least you can split this into two functions,navigateNext, andnavigatePrevious(passing a string to indicate direction is overly verbose and prone to typos). Also, if you want just one value out of the collection, just use the index accessor (collect(props.records)[0]) rather thanslice. \$\endgroup\$if if elseusage... \$\endgroup\$ifis dealing with direction, so if you split into two functions, you won't need that level. That just leavesif ... else ...\$\endgroup\$