当前位置:首页 > VUE

vue 折叠展开的实现

2026-01-21 01:35:06VUE

使用 v-ifv-show 控制显隐

通过 v-ifv-show 绑定布尔值动态控制元素的显示与隐藏。v-if 会销毁和重建 DOM 节点,适合切换频率低的场景;v-show 通过 CSS 的 display 属性控制,适合频繁切换的场景。

<template>
  <div>
    <button @click="isExpanded = !isExpanded">
      {{ isExpanded ? '折叠' : '展开' }}
    </button>
    <div v-if="isExpanded">需要折叠展开的内容</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isExpanded: false
    }
  }
}
</script>

结合 CSS 过渡动画

通过 Vue 的 <transition> 组件实现平滑的折叠展开动画效果。需配合 CSS 定义过渡属性(如 heightmax-height)。

<template>
  <div>
    <button @click="isExpanded = !isExpanded">切换</button>
    <transition name="fade">
      <div v-show="isExpanded" class="content">动画过渡的内容</div>
    </transition>
  </div>
</template>

<style>
.fade-enter-active, .fade-leave-active {
  transition: max-height 0.5s ease;
  max-height: 500px;
}
.fade-enter, .fade-leave-to {
  max-height: 0;
  overflow: hidden;
}
</style>

使用第三方组件库

UI 库如 Element UI 或 Ant Design Vue 提供现成的折叠面板组件(如 el-collapse),可直接调用。

<template>
  <el-collapse v-model="activeNames">
    <el-collapse-item title="标题" name="1">
      折叠面板内容
    </el-collapse-item>
  </el-collapse>
</template>

<script>
export default {
  data() {
    return {
      activeNames: ['1']
    }
  }
}
</script>

动态计算内容高度

通过 ref 获取 DOM 高度,动态设置 max-height 实现平滑动画。适用于内容高度不固定的场景。

vue 折叠展开的实现

<template>
  <div>
    <button @click="toggle">切换</button>
    <div ref="content" :style="{ maxHeight: isExpanded ? contentHeight + 'px' : '0' }">
      动态高度内容
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isExpanded: false,
      contentHeight: 0
    }
  },
  mounted() {
    this.contentHeight = this.$refs.content.scrollHeight
  },
  methods: {
    toggle() {
      this.isExpanded = !this.isExpanded
    }
  }
}
</script>

标签: vue
分享给朋友:

相关文章

vue实现本地数据存储

vue实现本地数据存储

使用 localStorage 或 sessionStorage Vue 中可以直接调用浏览器提供的 localStorage 或 sessionStorage API 进行数据存储。localSto…

vue实现摘要

vue实现摘要

Vue 实现摘要的方法 在 Vue 中实现文本摘要功能通常涉及截取文本的前部分内容并添加省略号。可以通过计算属性、过滤器或自定义指令来实现。 计算属性实现 在 Vue 组件中定义一个计算属性,用于截…

vue实现语音

vue实现语音

Vue 实现语音功能的方法 使用 Web Speech API Vue 可以结合 Web Speech API 实现语音识别和合成功能。Web Speech API 包含 SpeechRecognit…

vue实现闪烁

vue实现闪烁

Vue实现元素闪烁效果 使用CSS动画实现 通过Vue绑定class结合CSS动画实现闪烁效果,代码简洁且性能较好。 <template> <div :class="{ 'bl…

vue实现录像

vue实现录像

Vue 实现录像功能 在 Vue 中实现录像功能通常需要借助浏览器的 MediaDevices API 和 MediaRecorder API。以下是实现步骤: 获取用户摄像头和麦克风权限 使用 n…

vue 实现遮罩

vue 实现遮罩

Vue 实现遮罩层的方法 使用固定定位和透明背景 在Vue中实现遮罩层可以通过CSS固定定位结合透明背景色完成。创建一个全屏遮罩组件,利用position: fixed覆盖整个视窗。 <tem…