VUE 2.7 and newer versions
For Vue versions 2.7 and above, a composable has been introduced that allows you to easily create a reactive width and breakpoint name.
import { computed, onMounted, onUnmounted, ref } from "vue"
export const useBreakpoints = () => {
let windowWidth = ref(window.innerWidth)
const onWidthChange = () => windowWidth.value = window.innerWidth
onMounted(() => window.addEventListener('resize', onWidthChange))
onUnmounted(() => window.removeEventListener('resize', onWidthChange))
const type = computed(() => {
if (windowWidth.value < 550) return 'xs'
if (windowWidth.value >= 550 && windowWidth.value < 1200) return 'md'
else return 'lg' // Triggers when windowWidth.value >= 1200
})
const width = computed(() => windowWidth.value)
return { width, type }
}
You can integrate this in the setup method of your components.
const { width, type } = useBreakpoints()
Note: For simplicity and optimum performance, it is recommended to compute these values only once. To achieve this, implement them within effect scopes so that events are added/removed only within that scope. Alternatively, libraries like vueuse may handle this automatically for you.
Otherwise, initialize this logic close to the entry point, such as App.vue
, and manage it through your global state management system or import the composable from a library rather than using provide/inject.