Skip to content

Instantly share code, notes, and snippets.

@codeflorist
Created January 25, 2024 17:04
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 codeflorist/e52944d1ec4829c773bc64eb3aaf3d8c to your computer and use it in GitHub Desktop.
Save codeflorist/e52944d1ec4829c773bc64eb3aaf3d8c to your computer and use it in GitHub Desktop.
Nuxt 3 composable providing reactive variables regarding current breakpoint status.
/*
Nuxt 3 composable providing reactive variables
regarding current breakpoint status.
---------------------------------------------
Usage:
const { current, min, max } = useBreakpoints()
// returns current breakpoint
console.log(current.value) // e.g. 'md'
<div>{{current}}</div>
// returns true if current breakpoint is at least 'md'
console.log(min.md) // e.g. true
// returns true if current breakpoint is 'md' or less
console.log(max.md) // e.g. false
*/
export const useBreakpoints = () => {
type Breakpoint = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl' | '3xl' | '4xl'
type BreakpointStatus = {
xs: boolean | null
sm: boolean | null
md: boolean | null
lg: boolean | null
xl: boolean | null
'2xl': boolean | null
'3xl': boolean | null
'4xl': boolean | null
}
type Breakpoints = Record<Breakpoint, number>
const breakpoints: Breakpoints = {
'xs': 475,
'sm': 640,
'md': 768,
'lg': 1024,
'xl': 1280,
'2xl': 1536,
'3xl': 2048,
'4xl': 2398,
}
const screenWidth = ref(1024)
const current = ref<Breakpoint | null>(null)
const min = reactive<BreakpointStatus>({
'xs': null,
'sm': null,
'md': null,
'lg': null,
'xl': null,
'2xl': null,
'3xl': null,
'4xl': null,
})
const max = reactive<BreakpointStatus>({
'xs': null,
'sm': null,
'md': null,
'lg': null,
'xl': null,
'2xl': null,
'3xl': null,
'4xl': null,
})
watch(
screenWidth,
() => {
let newCurrent: Breakpoint | null = null
for (const key in breakpoints) {
min[key] = screenWidth.value >= breakpoints[key]
max[key] = screenWidth.value < breakpoints[key]
if (screenWidth.value >= breakpoints[key]) {
newCurrent = key
}
}
current.value = newCurrent
},
{ immediate: true }
)
if (process.client) {
screenWidth.value = window.innerWidth
window.addEventListener('resize', () => {
screenWidth.value = window.innerWidth
})
}
return {
current,
min,
max,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment