简体   繁体   中英

Why is position absolute needed for move transition when removing item from list in Vue.js

https://v2.vuejs.org/v2/guide/transitions.html#List-Move-Transitions gives an example in which when an item is removed from a list, the other items smoothly move in its place. For this to work the element is styled with:

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

I wonder why it doesn't work without this?

 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>

In this case, the position of the actively removed number is set from static to absolute , so that the element does not take up any space. Why is this important? The animation slides the rest of the numbers to the left, and if the removed item takes up space, this does not happen. You could substitute this for, for example, position: fixed or margin-right: -8px . All of these will animate the bounding box from about 18px (8px from the number, 10 from the margin) to 0px, neatly sliding the rest of the inline positioned items to the left.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM