DemuMesDataV/mixins/autoResize.js

77 lines
1.6 KiB
JavaScript
Raw Normal View History

2019-06-26 15:25:53 +08:00
import { debounce, observerDomResize } from '../util/index'
2019-01-16 16:56:11 +08:00
export default {
data () {
return {
dom: '',
width: 0,
height: 0,
debounceInitWHFun: '',
domObserver: ''
}
},
methods: {
2019-06-25 19:57:04 +08:00
async autoResizeMixinInit () {
const { initWH, getDebounceInitWHFun, bindDomResizeCallback, afterAutoResizeMixinInit } = this
2019-01-16 16:56:11 +08:00
await initWH()
getDebounceInitWHFun()
bindDomResizeCallback()
2019-06-25 19:57:04 +08:00
if (typeof afterAutoResizeMixinInit === 'function') afterAutoResizeMixinInit()
2019-01-16 16:56:11 +08:00
},
initWH () {
2019-06-25 19:57:04 +08:00
const { $nextTick, $refs, ref, onResize } = this
2019-01-16 16:56:11 +08:00
return new Promise(resolve => {
$nextTick(e => {
const dom = this.dom = $refs[ref]
this.width = dom.clientWidth
this.height = dom.clientHeight
2019-06-25 19:57:04 +08:00
if (typeof onResize === 'function') onResize()
2019-01-16 16:56:11 +08:00
resolve()
})
})
},
getDebounceInitWHFun () {
2019-06-26 15:25:53 +08:00
const { initWH } = this
2019-01-16 16:56:11 +08:00
this.debounceInitWHFun = debounce(100, initWH)
},
bindDomResizeCallback () {
2019-06-26 15:25:53 +08:00
const { dom, debounceInitWHFun } = this
2019-01-16 16:56:11 +08:00
this.domObserver = observerDomResize(dom, debounceInitWHFun)
window.addEventListener('resize', debounceInitWHFun)
},
unbindDomResizeCallback () {
2019-06-27 19:28:07 +08:00
let { domObserver, debounceInitWHFun } = this
2019-01-16 16:56:11 +08:00
domObserver.disconnect()
domObserver.takeRecords()
domObserver = null
window.removeEventListener('resize', debounceInitWHFun)
}
},
mounted () {
2019-06-25 19:57:04 +08:00
const { autoResizeMixinInit } = this
2019-01-16 16:56:11 +08:00
2019-06-25 19:57:04 +08:00
autoResizeMixinInit()
2019-01-16 16:56:11 +08:00
},
beforeDestroyed () {
const { unbindDomResizeCallback } = this
unbindDomResizeCallback()
}
2019-06-27 19:28:07 +08:00
}