Skip to content

Instantly share code, notes, and snippets.

@nhobi
Created May 6, 2021 22:50
Show Gist options
  • Save nhobi/2dc5675ae6f7263475c7f72d7e523ecf to your computer and use it in GitHub Desktop.
Save nhobi/2dc5675ae6f7263475c7f72d7e523ecf to your computer and use it in GitHub Desktop.
A Vue mixin that handles keeping the index for a given collection in bounds.
export default (collectionName, indexName = "selectedIndex", cycle = false) => {
return {
watch: {
[indexName](newValue, oldValue) {
if (this[collectionName] === undefined) {
return;
}
let highestIndex = this[collectionName].length - 1;
let indexIsTooHigh = newValue > highestIndex;
let indexIsTooLow = newValue < 0;
if (indexIsTooHigh) {
this[collectionName] = cycle ? 0 : oldValue;
}
if (indexIsTooLow && !cycle) {
this[collectionName] = cycle ? highestIndex : oldValue;
}
}
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment