Created
January 25, 2024 17:04
-
-
Save codeflorist/e52944d1ec4829c773bc64eb3aaf3d8c to your computer and use it in GitHub Desktop.
Nuxt 3 composable providing reactive variables regarding current breakpoint status.
This file contains hidden or 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
/* | |
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