VUE3+TS+CSS:三元运算实现页面动态布局
1. 动态class:页面动态呈现1/2/3列
- pageFormat的值根据不同显示效果动态切换,从而切换到不同的style上
- 静态、动态class合并写的话,放在
[ ]
里面
<template>
<div :class="['wrapper', pageFormat]">
<script>
//排版样式 1 style-1:单栏/左/右 style-12:双栏/左+右 style-123:三栏/左+中+右
let pageFormat: string = ref('style-1')
<style>
.style-1 {
.left,
.center,
.right {
left: 0;
width: calc(100% - 0.64rem);
}
}
.style-12 {
.left {
left: 0;
width: calc(32% - 0.64rem);
}
.right {
left: calc(32% - 0.16rem);
width: calc(68% - 0.32rem);
}
}
#####<style>
中定义div丝滑过渡效果
.left,
.right {
transition: all 0.2s ease;
position: absolute;
bottom: 1rem;
height: calc(100% - 0.64rem);
}
2. 动态style
1. 直接写在<template>
中
<div :style="pageFormat === 'style-1' ? 'max-width:94%' : 'width:100%'"></div>
2. 使用computed计算属性
- 适用于三元运算过于复杂,直接写在
<template>
中显得冗余沉重,放在computed
中,简化页面
<template>
<div :style="dynamicCardHeight" ></div>
<script>
- 必须
return
出去,不然无效
const dynamicCardHeight = computed(() => {
if (pageFormat.value === 'style-1') {
return 'height:72%'
}
else if (pageFormat.value != 'style-1' && repairedText.value.length === 0) {
return 'height:60%'
}
else if (repairedText.value.length > 0)
return 'height:34%'
}
)