循环中元素的 VueJS 转换?

VueJS transition on element in a loop?

这是我的代码:我想在每次更新数据时在 HelloWorld 组件上创建一个转换。过渡本身工作正常

  <transition name="fade">
    <p v-if="awesome">Vue is awesome</p>
  </transition>

这是我的 "cards" 动态创建的。

  <v-row no-gutters>
    <v-col cols="12" sm="4" md="4" v-for="(todo, index) in todos" v-bind:key="index">
      <v-card class="pa-2" outlined tile>
        <transition name="fade">
          <HelloWorld
            v-bind:todos="todos"
            v-bind:index="index"
            v-bind:class="(todos[index].done)?'green':'red'"
          />
        </transition>
      </v-card>
    </v-col>
  </v-row>

此处转换不起作用。

CSS 在这里:

<style scoped>
.top {
  background: blue;
  color: white;
  display: flex;
  justify-content: space-around;
  border-bottom: 2.5px solid black;
}

.fade-enter {
  opacity: 0;
}

.fade-enter-active {
  transition: opacity 1s;
}

.fade-leave {
}

.fade-leave-active {
  transition: 1s;
  opacity: 0;
}
</style>

为什么以及如何让它发挥作用?

如果你想在循环中为 each 元素设置动画,你必须:

  • transition 放在循环中。
  • 此外,使用 <transition-group>,而不仅仅是 <transition>
<v-row no-gutters>
  <transition-group name="fade-in" mode="out-in">
    <v-col cols="12" sm="4" md="4" v-for="(todo, index) in todos" v-bind:key="index">
      <v-card class="pa-2" outlined tile>
        <HelloWorld
          v-bind:todos="todos"
          v-bind:index="index"
          v-bind:class="(todos[index].done)?'green':'red'"
        />
      </v-card>
    </v-col>
  </transition-group>
</v-row>

而且我还建议您不要使用 1s 长动画,它太长了。做这样的事情:

CSS

.fade-in-enter-active {
  transition: all 0.5s ease;
}

.fade-in-leave-active {
  transition: all 0.5s ease;
}

.fade-in-enter, .fade-in-leave-to {
  position: absolute; /* add for smooth transition between elements */
  opacity: 0;
}

如果动画是抽搐的,你可以在enterleave-to CSS规则中添加position: absolute;(或者只针对leave-active)。

在 vue 文档中查看此页面:https://vuejs.org/v2/guide/transitions.html#List-Move-Transitions

<v-row no-gutters>
  <transition-group name="fade" class="row">
    <v-col cols="12" sm="4" md="4" v-for="(todo, index) in todos" :key="todo.randomKey">
      <v-card class="pa-2" outlined tile>
        <HelloWorld
          v-bind:todos="todos"
          v-bind:index="index"
          v-bind:class="(todos[index].done)?'green':'red'"
        />
      </v-card>
    </v-col>
   </transition-group>
 </v-row>

您需要进行多次编辑:

  1. 使用 <transition-group> 而不是 <transition>
  2. 使用 <transitiono-group> 包裹 <v-col>
  3. class="row" 添加到 <transition-group>
  4. index 替换为待办事项对象中的唯一键 例如 todo.idtodo.randomKey。使用 index 作为键就像 根本不用钥匙。