Last active
July 6, 2018 10:51
-
-
Save MeirionHughes/fce1ce986f7baab4940366f766cead10 to your computer and use it in GitHub Desktop.
Vue Resize Observer (no side effects)
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
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