Last active
December 6, 2019 20:32
-
-
Save samueleiche/56cd41c49a9c3a77494a9ce2439bdcde to your computer and use it in GitHub Desktop.
Breakpoint observer plugin for Vue.js using Vue observable.
This file contains 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
/** | |
* A media query matcher plugin for Vue.js, to listen to | |
* matching breakpoints. | |
* | |
* @plugin | |
* @example | |
* const breakpoints = { mdDevice: '(max-width: 959px)' }; | |
* Vue.use(BreakpointObserverPlugin, breakpoints); | |
* { | |
* computed: { | |
* mdDevice() { | |
* return this.$breakpointObserver.mdDevice; | |
* }, | |
* }, | |
* } | |
*/ | |
const BreakpointObserverPlugin = { | |
install(Vue, breakpoints) { | |
if (!breakpoints) { | |
throw new Error( | |
'Missing breakpoints options in BreakpointObserver.' | |
); | |
} | |
const state = {}; | |
for (const condition in breakpoints) { | |
const matcher = window.matchMedia(breakpoints[condition]); | |
state[condition] = matcher.matches; | |
matcher.addListener(() => { | |
state[condition] = matcher.matches; | |
}); | |
} | |
Vue.prototype.$breakpointObserver = Vue.observable(state); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment