You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Vue中v-for列表排序后部分CSS动画意外重启的问题

问题描述

我有一组数据,模板会使用该数据渲染为块列表,每个块都包含对应的时间条。列表顺序可随时更新,我发现每次更新列表顺序后,部分时间条的CSS动画会意外重启,以下是相关代码实现:

Vue 模板代码

<div id="app">
  <h2>TimeBars:</h2>
  <button @click="reOrder">
    打乱顺序
  </button>
  <ul class="listWrapper">
    <li v-for="(item, index) in list" class="row itemTest" :id="item.id" :key="item.id">
      <div class="timeBarContainer">
        <div class="timeBar" :style="{animationDuration: item.duration+ 's'}">
        </div>
        <div class="timeBarText">
          {{item.id}}
        </div>
      </div>
    </li>
  </ul>
  {{list}}
</div>

JS 代码

new Vue({
  el: "#app",
  data: {
    list: [
      { id: "bar1", done: false, duration: 10 },
      { id: "bar2", done: false, duration: 10 },
      { id: "bar3", done: true, duration: 10 },
      { id: "bar4", done: true, duration: 10 }
    ]
  },
  mounted(){
        console.log("DEBUG: 组件挂载", $("body"));
    $(".listWrapper").on('DOMNodeRemoved', function(e) {
      console.log(e.target, ' 被移除');
    });
  },
  methods: {
    reOrder: function(){
        this.list = shuffle(this.list);
      console.log("DEBUG: 当前列表:", JSON.stringify(this.list));
      function shuffle(array) {
          var currentIndex = array.length,  randomIndex;
          while (0 !== currentIndex) {
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex--;
            [array[currentIndex], array[randomIndex]] = [
              array[randomIndex], array[currentIndex]];
          }
          return JSON.parse(JSON.stringify(array));
        }
      }
    }
})

SCSS 代码

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
  >div{
    display: inline-block;
  }
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

.timeBarContainer{
  width: 100%;
  height: 15px;
  position: relative;
}

.timeBar{
  width: 100%;
  height: 100%;
  background-color: red;
  float: right;
  animation: timeBarAnimation 0s linear normal forwards;
}
.timeBarText{
  position: absolute;
}

@keyframes timeBarAnimation {
    0% {
        width: 100%;
    }
    100% {
        width: 0;
    }
}

补充说明

已验证排序后TimeBar组件并没有被卸载,但CSS动画仍然会被意外重启。


内容的提问来源于stack exchange,提问作者Chimoki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 20:06:03