案例为vue中公共可复用mixin文件
1、指定节点
import { ResizeObserver as ResizeObserverPolyfill } from '@juggle/resize-observer'
export default {
data() {
return {
containerObserver: null
}
},
created() {
const ResizeObserver = window.ResizeObserver || ResizeObserverPolyfill
this.containerObserver = new ResizeObserver(entries => {
const dom = entries[0].target
this.width = dom.offsetWidth
this.height = dom.offsetHeight
})
},
mounted() {
this.commonResize()
},
update() {
this.commonResize()
},
beforeDestroy() {
this.containerObserver.disconnect()
},
methods: {
commonResize() {
this.$nextTick(() => {
const dom = this.$refs['xxx'].$el
this.containerObserver.observe(dom)
this.width = dom.offsetWidth
this.height = dom.offsetHeight
})
}
}
}
2、批量节点控制
import { isArray, isFunction } from 'lodash'
import { ResizeObserver as ResizeObserverPolyfill } from '@juggle/resize-observer'
export default {
data() {
return {
borderObserver: null,
borderEleMap: new WeakMap(),
timer: null
}
},
created() {
const ResizeObserver = window.ResizeObserver || ResizeObserverPolyfill
this.borderObserver = new ResizeObserver(entries => {
entries.forEach(entry => {
let borderDom = this.borderEleMap.get(entry.target)
if (isArray(borderDom)) {
borderDom = borderDom[0]
}
if (borderDom && isFunction(borderDom.initWH)) {
borderDom = initWH()
}
})
})
},
mounted() {
this.commonResize()
},
update() {
this.commonResize()
},
beforeDestroy() {
this.borderObserver.disconnect()
clearTimeout(this.timer)
},
methods: {
commonResize() {
this.timer = setTimeout(() => {
Object.keys(this.$refs)
.filter(key => key.startWith('borderBox'))
.forEach(key => {
const borderDom = this.$refs[key]
if (borderDom) {
const borderEle = (isArray(borderDom) && borderDom.length > 0) ? borderDom[0] : borderDom.$el
if (borderEle && !this.borderEleMap.has(borderEle)) {
this.borderObserver.observe(borderEle)
this.borderEleMap.set(borderEle, borderDom)
}
}
})
}, 500)
}
}
}