是否有办法让Vue在新元素进入之前等待元素离开列表?目前,进入列表的新元素的动画与离开列表的元素的动画同时播放:
var SPEED = 3;
var app = new Vue({
el: '.container',
data: {
nodes: [
{id: 0, value: 5, name: "Alan"},
{id: 1, value: 15, name: "Bob"},
{id: 2, value: 25, name: "Charles"}
]
},
methods: {
enter(el, done) {
var bar = $(el).children(".bar");
TweenMax.fromTo(bar, SPEED, {width: 0}, {width: $(el).attr("width") * 10, onComplete: done});
},
leave(el, done) {
var bar = $(el).children(".bar");
TweenMax.fromTo(bar, SPEED, {width: $(el).attr("width") * 10}, {width: 0, onComplete: done});
},
swapBobDave() {
this.nodes = [
{id: 0, value: 5, name: "Alan"},
{id: 2, value: 25, name: "Charles"},
{id: 3, value: 35, name: "Dave"}
];
},
reset() {
this.nodes = [
{id: 0, value: 5, name: "Alan"},
{id: 1, value: 15, name: "Bob"},
{id: 2, value: 25, name: "Charles"}
];
}
}
});
body {
margin: 30px;
font-family: sans-serif;
}
.bar {
background-color: pink;
padding: 10px;
margin: 10px;
}
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.0/TweenMax.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<h1>Vue JS Hooks</h1>
<transition-group name="list" tag="div" v-on:enter="enter" v-on:leave="leave" v-bind:css="false" appear>
<div v-for="(node, index) in nodes" v-bind:key="node.id" v-bind:width="node.value">
<div class="bar" v-bind:style="{width: node.value + '%'}">{{node.name}}</div>
</div>
</transition-group>
<button type="button" class="btn btn-default" @click="swapBobDave">Add Dave and remove Bob</button>
<button type="button" class="btn btn-default" @click="reset">Reset</button>
</div>
要点:解释为什么离开栏在消失前没有到达width: 0
!
答案 0 :(得分:2)
这是transition-group
,因此对数组的每次更改都是不同的动画。如果您总是添加一个元素然后删除另一个元素,则可以使用enter
钩子上的setTimeout来实现它,持续时间为SPEED
。
enter(el, done) {
window.setTimeout( () => {
var bar = $(el).children(".bar");
TweenMax.fromTo(bar, SPEED, {width: 0}, {width: $(el).attr("width") * 10, onComplete: done});
}, SPEED * 1000 )
},
我还建议您以以下方式更改阵列
swapBobDave() {
this.nodes.splice(1,1);
this.nodes.push({id: 3, value: 35, name: "Dave"});
},
关于小节,它达到width: 0
,但CSS中有padding: 10px
。要解决此问题,您可以在其中的文本上直接添加边距,并删除栏上的填充。
希望它对您有帮助。