美文网首页
sizeHook vue dom尺寸监听 hook

sizeHook vue dom尺寸监听 hook

作者: copyLeft | 来源:发表于2020-04-07 11:23 被阅读0次
    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 ]
    }
    

    相关文章

      网友评论

          本文标题:sizeHook vue dom尺寸监听 hook

          本文链接:https://www.haomeiwen.com/subject/gpugphtx.html