<template><div><!-- 其他已有代码 --><el-row><el-col :span="isExpanded ? 24 : 20"><!-- 这里可以放置第一个 el-col 的内容 -->第一个 el-col 的内容</el-col></el-row><!-- 按钮移到 el-row 外面 --><button class="toggle-button":class="{ 'hidden': isExpanded }"@click="toggleColumns">切换显示状态</button></div>
</template><script setup>
import { ref } from 'vue';
import { ElRow, ElCol } from 'element-plus';// 用于记录是否展开的状态
const isExpanded = ref(false);// 点击按钮时切换状态
const toggleColumns = () => {isExpanded.value = !isExpanded.value;
};
</script><style scoped>
/* 其他已有样式 */
.toggle-button {/* 这里可以添加按钮的基础样式 */margin-top: 10px;
}.hidden {display: none;
}
</style>
上面我们是通过将按钮移到 el-row 外面,同时添加一个样式类来实现类似的视觉效果。
代码解释
- 按钮位置:把按钮放到了 el-row 外面,这样按钮的显示和隐藏就不会受 el-col 状态的影响。
- 样式绑定:使用 :class 动态绑定 hidden 类,当 isExpanded 为 true 时,按钮添加 hidden 类,将其 display 属性设置为 none 实现隐藏;当 isExpanded 为 false 时,按钮不添加 hidden 类,正常显示。
- toggleColumns 方法:保持不变,点击按钮时切换 isExpanded 的值,从而改变第一个 el-col 的 span 值。
通过这种方式,按钮不会随着 el-col 的隐藏而消失,能正确实现点击按钮切换显示状态的功能。