通过计算属性来动态调整面板旁边div的宽度
面板打开之前:
面板打开之后:
动态调整组件的宽度computed
用于计算依赖于isPanelVisible
的panelWidth
在面板所在的页面加上(面板所在的页面相当于父组件)
const baseWidth = 72
const panelWidth = computed(() => (isPanelVisible.value ? baseWidth : baseWidth + 28))
父组件中创建一个ref
并通过provide
函数暴露它:
import { ref, provide } from 'vue'
provide('panelWidth', panelWidth)
父组件完整代码:
<template>
<div class="about">
<el-container>
<el-header><Header></Header></el-header>
<el-main>
<Main></Main>
<transition name="slide-right">
<div class="panel" v-show="isPanelVisible"></div>
</transition>
</el-main>
</el-container>
</div>
</template>
<script setup>
import { ref, reactive, onMounted, computed, inject, provide } from 'vue'
import Header from '../components/HeadArea/Header.vue'
import Main from '../components/MainArea/Main.vue'
const store = inject('store')
const isPanelVisible = computed(() => store.state.PanelVisible)
//添加以下代码
const baseWidth = 72
const panelWidth = computed(() => (isPanelVisible.value ? baseWidth : baseWidth + 28))
provide('panelWidth', panelWidth)
onMounted(() => {})
</script>
在子组件中,使用inject
来接收这个ref
:
import { ref, onMounted, inject } from 'vue'
const panelWidth = inject('panelWidth')
然后在需要缩放的div上加上:
:style="{ width: panelWidth + 'vw' }"
子组件(Main组件)完整代码:
<template>
<div class="mainContainer" :style="{ width: panelWidth + 'vw' }">
<div class="sys-header" :style="{ width: panelWidth + 'vw' }">
<div class="sys-title" :style="{ width: panelWidth + 'vw' }">
<div class="sys-title-text">标题</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref, reactive, onMounted, inject } from 'vue'
const panelWidth = inject('panelWidth')
onMounted(() => {})
</script>
控制面板显隐可查看上一篇文章~