joken-前端工程师

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::
  404 随笔 :: 39 文章 :: 8 评论 :: 20万 阅读
<template>
  <div class='box'>
    <button @click="addItem">添加项目</button>
    <button @click="removeItem">删除项目</button>

    <TransitionGroup name="list" tag="ul" class="container">
      <li v-for="item in items" :key="item.id" class="list-item">
        {{ item.text }}
      </li>
    </TransitionGroup>
  </div>
</template>

<script lang='ts' setup>
import { ref } from 'vue';

interface ListItem {
  id: number;
  text: string;
}

const items = ref<ListItem[]>([
  { id: 1, text: '项目 1' },
  { id: 2, text: '项目 2' },
  { id: 3, text: '项目 3' },
]);

let nextId = 4;

const addItem = () => {
  items.value.push({
    id: nextId++,
    text: `项目 ${nextId - 1}`
  });
};

const removeItem = () => {
  if (items.value.length) {
    items.value.splice(Math.floor(Math.random() * items.value.length), 1);
  }
};
</script>

<style lang='scss' scoped>
.container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 20px;
  list-style: none;
}

.list-item {
  padding: 10px 20px;
  background: #42b883;
  color: white;
  border-radius: 4px;
  cursor: pointer;
}

// 进入和离开动画
.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}

// 进入动画起始状态和离开动画结束状态
.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

// 移动动画
.list-move {
  transition: transform 0.5s ease;
}
</style>

在这个例子中,我们将 TransitionGroup 的 name 属性设置为 "list",然后在 CSS 中定义了 .list-enter-active、.list-leave-active、.list-enter-from 和 .list-leave-to 这四个类,以实现进入和离开的过渡效果。

当项目进入时,.list-enter-active 和 .list-enter-from 类将应用于项目,而当项目离开时,.list-leave-active 和 .list-leave-to 类将应用于项目。这些类名是根据 name 属性的值自动生成的。

例如,如果您将 name 属性设置为 "fade",那么您需要在 CSS 中定义 .fade-enter-active、.fade-leave-active、.fade-enter-from 和 .fade-leave-to 这四个类,以实现进入和离开的过渡效果。

posted on   joken1310  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示