Skip to content

Instantly share code, notes, and snippets.

@MeirionHughes
Last active July 6, 2018 10:51
Show Gist options
  • Save MeirionHughes/fce1ce986f7baab4940366f766cead10 to your computer and use it in GitHub Desktop.
Save MeirionHughes/fce1ce986f7baab4940366f766cead10 to your computer and use it in GitHub Desktop.
Vue Resize Observer (no side effects)
import Vue from 'vue'
import ResizeObserver from 'resize-observer-polyfill';
declare module 'vue/types/vue' {
interface Vue {
observe(ref: string, cb: (ref: DOMRectReadOnly) => void);
unobserve(ref: string);
}
}
export default {
install(Vue) {
Vue.mixin({
destroyed() {
if (this._ro) {
this._ro.disconnect();
delete this._ro;
delete this._roo;
}
}
});
Vue.prototype.observe = function (ref, cb) {
this._roo = this._roo || new Map();
this._ro = this._ro || new ResizeObserver((entries) => {
for (let item of entries) {
if (this._roo.has(item.target)) {
this._roo.get(item.target)(item.contentRect);
}
}
});
const elmt = this.$refs[ref];
if (elmt) {
this._roo.set(elmt, cb);
this._ro.observe(elmt);
}
};
Vue.prototype.unobserve = function (ref) {
const elmt = this.$refs[ref];
if (elmt && this._roo && this._roo.has(elmt)) {
this._roo.delete(elmt);
this._ro.unobserve(elmt);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment