当前位置:首页 > VUE

vue 折叠展开的实现

2026-01-21 01:35:06VUE

使用 v-ifv-show 控制显隐

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

vue 折叠展开的实现

<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)。

vue 折叠展开的实现

<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 实现平滑动画。适用于内容高度不固定的场景。

<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路由实现内部切换

Vue 路由实现内部切换的方法 Vue Router 是 Vue.js 官方的路由管理器,用于实现单页应用(SPA)的页面切换。以下是几种常见的内部路由切换方式: 使用 <router-lin…

vue实现字母添加排序

vue实现字母添加排序

实现字母添加排序的方法 在Vue中实现字母添加排序功能,可以通过以下步骤完成: 创建Vue实例并定义数据 new Vue({ el: '#app', data: { letters…

vue实现弹窗

vue实现弹窗

Vue 实现弹窗的常见方法 使用组件化方式封装弹窗 创建一个独立的弹窗组件(如 Modal.vue),通过 v-if 或 v-show 控制显示隐藏: <template> <…

vue实现RTMP

vue实现RTMP

Vue 中实现 RTMP 流播放 RTMP(Real-Time Messaging Protocol)是一种用于实时音视频流传输的协议。在 Vue 中实现 RTMP 播放通常需要借助第三方库或播放器。…

vue核心实现

vue核心实现

Vue 核心实现原理 Vue.js 的核心实现主要包括响应式系统、虚拟 DOM、模板编译和组件化机制。以下是关键实现原理的详细说明: 响应式系统 Vue 使用 Object.defineProper…

轮播vue实现

轮播vue实现

使用 Vue 实现轮播功能 基础轮播实现 安装依赖(如使用 Swiper): npm install swiper vue-awesome-swiper 组件代码示例: <template&…