Skip to content

Instantly share code, notes, and snippets.

@loilo
Created April 28, 2022 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loilo/f229e20870228dca6d866b748cb07061 to your computer and use it in GitHub Desktop.
Save loilo/f229e20870228dca6d866b748cb07061 to your computer and use it in GitHub Desktop.
useElementBreakpoints – Vue Composable for Element breakpoints
// useElementBreakpoints is a Vue 3 composable that matches an element's width (or height) against a set of predefined breakpoints
// It needs @vueuse/core to be installed and uses an equivalent breakpoints input as well as an equivalent returned API
import { computed, Ref } from 'vue'
import { useElementSize, MaybeElementRef } from '@vueuse/core'
export type Breakpoints<K extends string = string> = Record<K, number>
export type ElementBreakpointsOptions = { dimension: 'width' | 'height' }
/**
* Reactive element breakpoints
*/
export function useElementBreakpoints<K extends string>(
target: MaybeElementRef,
breakpoints: Breakpoints<K>,
{ dimension = 'width' }: Partial<ElementBreakpointsOptions> = {}
) {
let size = useElementSize(target)[dimension]
let shortcutMethods = Object.keys(breakpoints).reduce(
(shortcuts, breakpoint) => {
Object.defineProperty(shortcuts, breakpoint, {
get: () => computed(() => size.value >= breakpoints[breakpoint as K]),
enumerable: true,
configurable: true,
})
return shortcuts
},
{} as Record<K, Ref<boolean>>
)
return {
greater: (breakpoint: K) =>
computed(() => size.value >= breakpoints[breakpoint]),
smaller: (breakpoint: K) =>
computed(() => size.value < breakpoints[breakpoint]),
between: (lowerBreakpoint: K, upperBreakpoint: K) =>
computed(
() =>
size.value >= breakpoints[lowerBreakpoint] &&
size.value < breakpoints[upperBreakpoint]
),
isGreater: (breakpoint: K) => size.value >= breakpoints[breakpoint],
isSmaller: (breakpoint: K) => size.value < breakpoints[breakpoint],
isInBetween: (lowerBreakpoint: K, upperBreakpoint: K) =>
size.value >= breakpoints[lowerBreakpoint] &&
size.value < breakpoints[upperBreakpoint],
...shortcutMethods,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment