Skip to content

Instantly share code, notes, and snippets.

@samueleiche
Last active December 6, 2019 20:32
Show Gist options
  • Save samueleiche/56cd41c49a9c3a77494a9ce2439bdcde to your computer and use it in GitHub Desktop.
Save samueleiche/56cd41c49a9c3a77494a9ce2439bdcde to your computer and use it in GitHub Desktop.
Breakpoint observer plugin for Vue.js using Vue observable.
/**
* 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