vue3中provide,inject 响应式传递

问题背景

在使用element-plus 表格组件时,需要固定表头,高度自适应页面大小,在父组件中获取容器的高度,使用provide传递子组件中,子组件使用inject接收父组件传递的高度,

vue官网中对provide和inject传递响应式数据是这么解释的

16377560148187.png

父组件

import {ref, provide,defineComponent,onMounted} from 'vue' 
export default defineComponent({
  setup(){
      const tableHeight= ref(0)
      const getTableHeight = async () => {
        let container = document.querySelector('.statistics-body')
        let height = container.clientHeight
        tableHeight.value = height
      }
      // 向子组件注入
      provide('tableHeight', tableHeight)
      onMounted(() => {
        getTableHeight()
      })
    }
})

子组件

import { inject} from 'vue' 
export default defineComponent({
  setup(){
      const tableHeight = inject('tableHeight')
      return{
          tableHeight 
      }
    }
})

实际效果,通过watch监听可以拿到最新的容器高度,但是页面中表格 max-height="0px" ,表格没有显示出来

分析原因

因为在父子组件挂载顺序 父组件(setup) -> 子组件(setup) -> 子组件(mounted) -> 父组件(mounted) 因为在父组件mounted获取容器高度时,子组件已经挂载完毕,所以及时子组件拿到了最新的高度,也无法在页面中更新

解决办法

nextTick 官网

16377569171295.png

修改父组件代码

import {ref, provide,defineComponent,onMounted,nextTick} from 'vue' 
export default defineComponent({
  setup(){
      const tableHeight= ref(0)
      const getTableHeight = async () => {
        await nextTick()  // 
        let container = document.querySelector('.statistics-body')
        let height = container.clientHeight
        tableHeight.value = height
      }
      // 向子组件注入
      provide('tableHeight', tableHeight)
      onMounted(() => {
        getTableHeight()
      })
    }
})

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容