首页 > 解决方案 > Vue.js 过渡组删除并再次添加

问题描述

我在 Vue 单页模板中有一个表单列表。模板以异步方式将内容加载为数组,然后对其进行迭代以创建表单。该列表是 a 的孩子<transition-group>。每个表单都有一个向上/向下按钮,使它们能够在列表中上下移动;当向上/向下单击时,上方/下方的表单使用过渡动画与单击的表单交换。

当页面在模板的created()钩子期间加载异步内容时,列表的动画绝对没问题。

然而,当列表为空时created()或列表中的所有表单被删除并随后添加新表单时,订单动画停止运行。没有其他任何问题,所有的反应性等都很好。鉴于以下情况,是否有解决此错误的方法?

如果有用,我将尝试在下面提供最简短的存根:

[HTML]

<template>
...
<transition-group v-if="sections.length"
                          name="flip-list"
                          tag="div">
  <div v-for="(section, i) in sortedOrder"
       :key="sortedOrder[i].id>
    <div>
       <button @click.prevent="decrementOrder(section.order, i)">
         <i class="fas fa-chevron-up"></i>
       </button>
       <button @click.prevent="incrementOrder(section.order, i)">
         <i class="fas fa-chevron-down"></i>
       </button>
       ... FORM FIELDS ETC ...
    </div>
  </div>
</transition-group>
...
</template>

[JS]

computed: {
  sortedOrder () {
      let sorted = this.sections
      return sorted.sort((a, b) => { return a.order - b.order })
    }  
},
methods: {
   ...
   addSection () {
      let newSection = {
        id: -1,
        order: this.sections.length,
        ...
      }
      let i = this.sections.push(newSection) - 1
      ...
    },
    deleteSection (id) {
      let wasSpliced = 0
      this.sections.forEach(function (section, i) {
        if (section.id === id) {
          this.sections.splice(i, 1)
          if (this.sections.length && this.sections.length > i) { 
            --this.sections[i].order
          }
          wasSpliced = 1
        } else if (wasSpliced) {
          --this.sections[i].order
        }
      }.bind(this))
    },
    decrementOrder (order, i) {
      if (order > 0) {
        this.sections.forEach((it, j) => {
          if (it.order + 1 === order) {
            ++this.sections[j].order
            --this.sections[i].order
          }
        })
      }
    },
    incrementOrder (order, i) {
      if (order <= this.sections.length - 1) {
        this.sections.forEach((it, j) => {
          if (it.order - 1 === order) {
            --this.sections[j].order
            ++this.sections[i].order
          }
        })
      }
    }
    ...
}

[CSS]

...css
.flip-list-move {
transition: transform 1s;
}

标签: javascripthtmlcssvue.jscss-transitions

解决方案


推荐阅读