vue实现动画效果展开与收起(vue折叠动画效果)

使用过CSS transition属性的童鞋们应该都清楚,当元素在过渡开始或者结束时的高度为auto时,动画是不生效的;那么如何才能实现元素高度的改变动画效果呢?本篇文章将为大家提供一个基于Vue3的非常简洁的解决方案。

要实现高度的改变动画,我们需要在动画进行之前为元素设置准确的高度。

当元素由可见变为隐藏状态时,我们需要先获取元素的计算高度,将其设置到style属性上,然后执行一个触发浏览器渲染引擎重绘的动作,然后再将高度设置为0,这样高度的改变动画就会正常进行。

当元素由隐藏变为可见状态时,我们需要先将高度设置为auto,然后获取元素的计算高度,再将高度设置为0,然后执行一个触发浏览器渲染引擎重绘的动作,然后再将高度设置为计算高度,这样高度的改变动画就会正常进行。

现在,根据以上实现原理分析,我们创建一个高度的改变动画通用组件CollapseTransition.vue。该组件非常简单,仅需30多行代码。我几乎每行代码都有注释,大家应该能看懂吧?

<template>
  <transition v-bind="listeners">
    <!-- 当visible的值发生改变时,过渡组件的监听器就会触发 -->
    <div v-show="visible" class="x-collapse-transition">
      <slot />
    </div>
  </transition>
</template>
<script setup>
defineProps({ visible: Boolean })
const listeners = {
  // 元素由隐藏变为可见
  onEnter (/** @type {HTMLElement} */ el) {
    el.style.height = 'auto' // 将高度设为auto,是为了获取该元素的计算高度
    const endHeight = window.getComputedStyle(el).height // 计算高度
    el.style.height = '0px' // 将高度再设置为0
    el.offsetHeight // 强制重绘,重绘后再改变高度才会产生动画
    el.style.height = endHeight // 设置为计算高度
  },
  onAfterEnter (/** @type {HTMLElement} */ el) {
    el.style.height = null // 过渡进入之后,将高度恢复为null
  },
  // 元素由可见变为隐藏
  onLeave (/** @type {HTMLElement} */ el) {
    el.style.height = window.getComputedStyle(el).height // 计算高度
    el.offsetHeight // 强制重绘,重绘后再改变高度才会产生动画
    el.style.height = '0px' // 将高度设置为0
  },
  onAfterLeave (/** @type {HTMLElement} */ el) {
    el.style.height = null // 过渡离开之后,将高度恢复为null
  }
}
</script>
<style lang="scss">
  .x-collapse-transition {
    overflow: hidden;
    transition: height .22s ease-in-out;
  }
</style>

以上就是实现高度的改变动画的通用组件源码,童鞋们理解了吗?是不是非常简单?现在,我们实现折叠面板组件。使用过element-ui这样的UI库的童鞋们应该都知道,折叠面板是由两个组件折叠面板Collapse和折叠面板项CollapseItem组合而成;

现在,我们先实现CollapseItem.vue组件。为了节省篇幅,我将源码中的空行全部去掉了,缩进比较规范,自认为可读性还行;源码如下,一共30多行,我直接在源码中添加了注释,就不过多解释了。

<template>
  <div :class="[cls, { 'is-active': isActive }]">
    <div :class="`${cls}_header`" @click="onToggle">
      <div :class="`${cls}_title`">
        <slot name="title">{{ title }}</slot>
      </div>
      <i :class="['x-icon-arrow-right', `${cls}_arrow`, { 'is-active': isActive }]"></i>
    </div>
    <x-collapse-transition :visible="isActive">
      <div :class="`${cls}_content`">
        <slot />
      </div>
    </x-collapse-transition>
  </div>
</template>
<script setup>
import { computed, inject } from 'vue'
import { COLLAPSE_INJECT_KEY } from '../../constants' // 当它是个字符串常量就行
import { N, S, B } from '../../types' // N: Number, S: String, B: Boolean
import { genKey } from '../../utils' // 生成唯一性的数值key,之前的文章中有源码
import XCollapseTransition from './CollapseTransition.vue' // 折叠动画组件
const props = defineProps({
  name: [S, N],
  title: S,
  disabled: B
})
const collapse = inject(COLLAPSE_INJECT_KEY, '') // 注入折叠面板组件提供的一些属性和方法
const cls = 'x-collapse-item'
const idKey = computed(() => props.name || genKey()) // 如果没提供name,我们生成一个key
const isActive = computed(() => collapse.includes(idKey.value)) // 是否展开状态
function onToggle () { // 内容可见时隐藏,隐藏时可见
  collapse.updateModel(idKey.value)
}
</script>

这是CollapseItem.vue组件的样式。

@import './common/var.scss';
.x-collapse-item {
  font-size: 13px;
  background-color: #fff;
  color: $--color-text-primary;
  border-bottom: 1px solid $--border-color-lighter;
  &:first-child {
    border-top: 1px solid $--border-color-lighter;
  }
  &_header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 48px;
    cursor: pointer;
  }
  &_content {
    line-height: 1.8;
    padding-bottom: 25px;
  }
  &_arrow {
    margin-right: 8px;
    transition: transform .2s;
    &.is-active {
      transform: rotate(90deg);
    }
  }
}

现在,我们实现Collapse.vue组件。该组件仍然只有30多行,大家理解起来应该很轻松,我就直接在源码里添加注释作为讲解了;

<template>
  <div class="x-collapse">
    <slot />
  </div>
</template>
<script setup>
import { provide, reactive, ref, watch } from 'vue'
import { COLLAPSE_INJECT_KEY } from '../../constants' // 一个字符串常量
import { S, B, A } from '../../types' // 参看CollapseItem组件
const props = defineProps({
  modelValue: [S, A], // Vue3使用modelValue取代了Vue2中的value
  accordion: B // 是否手风琴模式,手风琴模式只能有1个面板项是展开状态
})
const emit = defineEmits(['update:modelValue', 'change'])
function emitValue (v) {
  emit('update:modelValue', v) // 与props.modelValue结合实现双向数据绑定
  emit('change', v)
}
const model = ref(props.modelValue)
watch(() => props.modelValue, v => model.value = v)
provide(COLLAPSE_INJECT_KEY, { // 提供2个方法用于注入子组件,给子组件调用
  includes (v) { // 根据面板的key,判断是否包含该面板项
    return props.accordion ? model.value === v : (model.value || []).includes(v)
  },
  updateModel (v) { // 更新面板项的内容折叠和展开状态
    const { value } = model
    if (props.accordion) {
      model.value = value === v ? null : v
      emitValue(model.value)
    } else {
      if (!value) model.value = []
      const index = model.value.indexOf(v)
      index > -1 ? model.value.splice(index, 1) : model.value.push(v)
      emitValue(model.value)
    }
  }
})
</script>

以上就是折叠面板组件的实现。包括折叠动画组件,一共仅需不到150行代码,是不是非常简单?童鞋们都理解了吗?不管有什么疑问,童鞋们都可以问我。感谢阅读!

vue实现动画效果展开与收起(vue折叠动画效果)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发表评论

登录后才能评论