vue3中provide,inject 响应式传递
2021-11-27 本文已影响0人
有你有团
问题背景
在使用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()
})
}
})