【Vue3】transition-group 过渡列表

1. 基本使用

transition-grouptransition 的用法基本上是一样的。

<template>
  <div class="content">
    <button @click="add">addbutton>
      <button @click="pop">popbutton>
    <div class="wrap">
      
      <transition-group
      leave-active-class="animate__animated animate__hinge"
      enter-active-class="animate__animated animate__bounceIn"
      >
        <div class="item" v-for="item in list" :key="item">{{ item }}div>
      transition-group>
    div>
  div>
template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import 'animate.css'
const list = reactive<number[]>([1, 2, 3, 4, 5, 6])
const add = () => {
  list.push(list.length+1)
}
const pop = () => {
  list.pop()
}
script>

<style scoped>
.box {
  height: 200px;
  width: 200px;
  background-color: red;
}

.wrap {
  display: flex;
  flex-wrap: wrap;
  word-break: break-all;
  border: 1px solid #ccc;

  .item {
    margin: 10px;
    font-size: 20px;
  }
}
style>

【Vue3】transition-group 过渡列表_第1张图片

2. 列表的移动过渡

先看一下new Array(81)Array.apply(null, {length: 81})的区别:

【Vue3】transition-group 过渡列表_第2张图片
Array.apply(null, {length: 81})可以帮我们初始化好每一项数据,每一项的值都是 undefined

过程中,需要使用lodash库,但是npm install lodash -D安装之后会有报错,原因是缺少声明文件,需要执行npm install @types/lodash -D 来安装 ts 的声明文件库,lodash库中的_.shuffle()方法可以创建一个被打乱值的数组。

<template>
  <div class="content">
    <button @click="random">randombutton>
    <transition-group move-class="trans" class="wraps" tag="div">
      <div class="items" :key="item.id" v-for="item in list">
        {{ item.number }}
      div>
    transition-group>
  div>
template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import _ from 'lodash';
let list = ref(Array.apply(null, { length: 81 } as number[]).map((_, index) => {
  return {
    id: index,
    number: (index % 9) + 1
  }
}))
console.log(list.value);
const random = () => {
  list.value = _.shuffle(list.value);
}
script>

<style scoped lang="less">
.wraps {
  display: flex;
  flex-wrap: wrap;
  width: calc(25px * 10 + 9px);

  .items {
    width: 25px;
    height: 25px;
    border: 1px solid #ccc;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.trans {
  transition: all 5s;
}
style>

【Vue3】transition-group 过渡列表_第3张图片

【Vue3】transition-group 过渡列表_第4张图片
【Vue3】transition-group 过渡列表_第5张图片

3. 状态过渡

<template>
  <div>
    <input v-model="num.current" step="20" type="number">
    <div>
      {{ num.tweenedNumber.toFixed(2) }}
    div>
  div>
template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue';
import gsap from 'gsap'
// tweenedNumber是配置项,gsap内部做了num.tweenedNumber = newValue的处理, reactive是默认deep: true,触发响应式
const num = reactive({
  current: 0,
  tweenedNumber: 0,
})
watch(() => num.current, (newValue, oldValue) => {
  gsap.to(num, {
    duration: 1, // 1秒
    tweenedNumber: newValue,
  })
})
script>

<style scoped lang="less">style>

【Vue3】transition-group 过渡列表_第6张图片

你可能感兴趣的:(Vue,javascript,vue.js,前端)