从Vue.js中的列表中删除项目时,为什么移动过渡需要绝对位置

时间:2018-10-20 02:30:40

标签: javascript css animation vue.js

https://vuejs.org/v2/guide/transitions.html#List-Move-Transitions给出了一个示例,其中当一个项目从列表中删除时,其他项目平稳地移动到其位置。为此,元素的样式设置为:

.list-complete-leave-active {
  position: absolute;
}

我想知道为什么没有这个就行不通?

new Vue({
  el: '#list-complete-demo',
  data: {
    items: [1,2,3,4,5,6,7,8,9]
  },
  methods: {
    randomIndex: function () {
      return Math.floor(Math.random() * this.items.length)
    },
    remove: function () {
      this.items.splice(this.randomIndex(), 1)
    }
  }
})
.list-complete-item {
  transition: all 1s;
  display: inline-block;
  margin-right: 10px;
}
.list-complete-leave-to {
  opacity: 0;
  transform: translateY(30px);
}
.list-complete-leave-active {
  position: absolute;
}
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.1/lodash.min.js"></script>

<div id="list-complete-demo" class="demo">
  <button v-on:click="remove">Remove</button>
  <transition-group name="list-complete" tag="p">
    <span
      v-for="item in items"
      v-bind:key="item"
      class="list-complete-item"
    >
      {{ item }}
    </span>
  </transition-group>
</div>

1 个答案:

答案 0 :(得分:2)

在这种情况下,主动删除的数字的位置从static设置为absolute,因此元素不会占用任何空间。为什么这很重要?动画会将其余的数字向左滑动,如果删除的项目占用了空间,则不会发生这种情况。您可以用position: fixedmargin-right: -8px代替。所有这些都会使边界框从大约18像素(数字为8像素,边距为10像素)到0像素进行动画处理,将其余的内联定位项整齐地滑动到左侧。

new Vue({
  el: '#list-complete-demo',
  data: {
    items: [1,2,3,4,5,6,7,8,9]
  },
  methods: {
    randomIndex: function () {
      return Math.floor(0)
    },
    remove: function () {
      this.items.splice(this.randomIndex(), 1)
    }
  }
})
.list-complete-item {
  transition: all 10s;
  display: inline-block;
  margin-right: 10px;
}
.list-complete-leave-to {
  opacity: 0;
  transform: translateY(30px);
}
.list-complete-leave-active {
  position: absolute;
}
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.1/lodash.min.js"></script>

<div id="list-complete-demo" class="demo">
  <button v-on:click="remove">Remove</button>
  <transition-group name="list-complete" tag="p">
    <span
      v-for="item in items"
      v-bind:key="item"
      class="list-complete-item"
    >
      {{ item }}
    </span>
  </transition-group>
</div>