Skip to content

Instantly share code, notes, and snippets.

@AlexVipond
Last active May 8, 2021 02:41
Show Gist options
  • Save AlexVipond/4235dce783a3e63bf1d75beed89025be to your computer and use it in GitHub Desktop.
Save AlexVipond/4235dce783a3e63bf1d75beed89025be to your computer and use it in GitHub Desktop.
Use Vue's computed getters and setters to simplify APIs that might otherwise be esoteric for other developers
<script lang="ts">
import { useNavigable } from 'path/to/useNavigable'
export default {
setup () {
const myImages = [...]
const { location, next, previous } = useNavigable(myImages)
return {
myImages,
location,
next,
previous,
}
}
}
</script>
<template>
<button @click="previous">
</button>
<div>
<button
v-for="(image, index) in myImages"
:key="image.src"
@click="() => location = index"
>
<img :src="image.src" :alt="image.alt" />
</button>
</div>
<button @click="next">
</button>
</template>
import { ref, computed } from 'vue'
import { Ref, WritableComputedRef } from 'vue'
export type Navigable = {
location: WritableComputedRef<number>,
next: () => void,
previous: () => void,
}
export function useNavigable (array: any[]): Navigable {
const esotericApi = ref(new EsotericClassImplementation(array))
const location = computed({
get: () => esotericApi.value.location,
set: number => {
esotericApi.value.location = number
},
})
return {
location,
next: () => esotericApi.value.next(),
previous: () => esotericApi.value.previous(),
}
}
class EsotericClassImplementation {
array: any[]
location: number
constructor (array) {
this.array = array
this.location = 0
}
next () {
this.location = this.location === this.array.length - 1
? 0
: this.location + 1
}
previous () {
this.location = this.location === 0
? this.array.length - 1
: this.location - 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment