Vue内置组件TransitionGroup
封面图
•
2025-11-19
•
Vue
0
0
0
0
在 Vue 中,`<TransitionGroup>` 是一个**内置组件**,用于对**列表项**(如 `<ul>`、`<ol>` 或 `<div>` 等容器内的多个元素)进行过渡动画。它与 `<Transition>` 类似,但专门用于处理动态列表的进入、离开和移动动画。 --- ## ✅ 一、基本用法 ```vue <template> <div> <button @click="addItem">添加</button> <transition-group name="fade" tag="ul"> <li v-for="(item, index) in items" :key="item.id"> {{ item.text }} </li> </transition-group> </div> </template> <script> export default { data() { return { items: [ { id: 1, text: 'Item 1' }, { id: 2, text: 'Item 2' } ], nextId: 3 }; }, methods: { addItem() { this.items.push({ id: this.nextId++, text: `Item ${this.nextId - 1}` }); } } }; </script> <style> .fade-enter-active, .fade-leave-active { transition: opacity 0.5s; } .fade-enter, .fade-leave-to { opacity: 0; } </style> ``` --- ## 🔍 二、关键特性 ### 1. **支持列表中的元素进入、离开、移动** - `enter`:新元素加入时 - `leave`:元素被移除时 - `move`:元素位置变化时(比如排序) > 注意:`move` 动画需要配合 `v-move` 类使用。 ### 2. **可以指定 `tag` 属性** - 默认情况下,`<TransitionGroup>` 会渲染为一个 `span`,如果你希望渲染为 `<ul>` 或 `<ol>`,可以通过 `tag="ul"` 来指定。 ### 3. **必须使用 `key` 属性** - 每个列表项必须有唯一的 `key`,否则 Vue 无法正确识别哪些元素是新增或删除的。 --- ## 🎨 三、CSS 过渡类名 | 类名 | 触发时机 | |-------------------|------------------| | `.name-enter` | 元素进入时 | | `.name-enter-active` | 进入时的过渡状态 | | `.name-enter-to` | 进入结束状态 | | `.name-leave` | 元素离开时 | | `.name-leave-active` | 离开时的过渡状态 | | `.name-leave-to` | 离开结束状态 | | `.name-move` | 元素移动时 | > `name` 是你通过 `name` 属性设置的名称,例如 `name="fade"`。 --- ## ⚠️ 四、注意事项 - **不要将 `<TransitionGroup>` 渲染为 `<div>`**,因为 `<div>` 是块级元素,可能导致布局问题。 - 如果你想让整个列表作为一个整体过渡,可以使用 `tag="ul"` 或 `tag="ol"`。 - `TransitionGroup` 不支持 `mode` 属性(如 `in-out` 或 `out-in`),因为它处理的是多个元素。 --- ## 🧠 五、进阶用法:移动动画(Move) 要实现元素移动时的过渡效果(比如列表排序时的动画): ```vue <template> <div> <button @click="sortItems">排序</button> <transition-group name="slide" tag="ul"> <li v-for="item in items" :key="item.id">{{ item.text }}</li> </transition-group> </div> </template> <script> export default { data() { return { items: [ { id: 1, text: 'Item 1' }, { id: 2, text: 'Item 2' }, { id: 3, text: 'Item 3' } ] }; }, methods: { sortItems() { this.items = this.items.sort(() => Math.random() - 0.5); } } }; </script> <style> .slide-enter-active, .slide-leave-active { transition: all 0.5s ease; } .slide-enter, .slide-leave-to { opacity: 0; transform: translateX(30px); } .slide-move { transition: transform 0.5s ease; } </style> ``` --- ## ✅ 总结 | 特性 | 说明 | |------------------|--------------------------------------------| | 组件类型 | 内置组件 | | 用途 | 对列表项进行过渡动画 | | 必须属性 | `key` | | 支持动画类型 | enter, leave, move | | 可以设置的 tag | `ul`, `ol`, `div` 等(推荐使用列表标签) | | 不支持的属性 | `mode` | --- 如果你有任何关于 `<TransitionGroup>` 的具体问题(比如如何实现某种动画效果),欢迎继续提问!
上一篇:
Vue插件
标题录入,一次不能超过6条
留言
评论