Created
May 6, 2021 22:50
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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