sizeHook vue dom尺寸监听 hook
2020-04-07 本文已影响0人
copyLeft
chart.gif
使用例子
<template>
<div class="home" ref='element'>
<div>
<Card style='margin: 20% auto; width: 600px' title=''>
<h4>
width: {{ size.width }}
/
height: {{ size.height }}
</h4>
</Card>
</div>
</div>
</template>
<script>
// import { ref } from '@vue/composition-api'
import sizeHook from '@/hooks/sizeHook'
export default {
setup(){
const [ size, element ] = sizeHook()
return {
element,
size
}
}
}
</script>
实现
import { ref, watch, computed } from '@vue/composition-api'
import ResizeObserver from 'resize-observer-polyfill';
/**
* dom尺寸监听
* @param { dom ref } initDom 初始dom对象
* @returns { [ state, element ] } state dom尺寸 element 绑定ref
*
* @example
*
* setup(){
* const [ size, element ] = sizeHook()
* return{ size, element }
* }
*
* 模板
*
* <h4>
width: {{ size.width }}
/
height: {{ size.height }}
</h4>
*
*/
export default function sizeHook(initDom={}){
const element = ref(null)
const state = ref({
width: ( initDom.value || {} ).clientWidth,
height: ( initDom.value || {} ).clientHeight
})
const resizeObserver = ref(null)
const targetElement = computed(() => initDom.value || element.value)
watch(() => targetElement.value, () => {
if(resizeObserver.value){ resizeObserver.disconnect() }
if(!targetElement.value) return
resizeObserver.value = new ResizeObserver( entries => {
entries.forEach( entry => {
state.value = {
width: entry.target.clientWidth,
height: entry.target.clientHeight,
}
})
})
resizeObserver.value.observe(targetElement.value);
})
return [ state, element ]
}