本文介绍了在 VueJS 中平滑地为 v-show 设置动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在 Vuejs 中使用转换为两个 div 设置动画.下面是我使用的代码(jsfiddle).但不知道为什么它不起作用
https://jsfiddle.net/k6grqLh1/16/
vue
<div><transition name="淡入淡出"><div v-show="show"><div class="box Yellow"></div>
<transition name="淡入淡出"><div v-show="!show"><div class="box blue"></div>
<a href="#" @click="show = !show">更改</a>
css
.fade-enter-active, .fade-leave-active {过渡:不透明度 0.5s}.fade-enter, .fade-leave-to/* .fade-leave-active in
js
var vm = new Vue({el: '#vue-instance',数据: {显示:真实}});
解决方案
需要在每个div中添加key,除了在fiddle中添加vue 2.x之外,还需要做如下修改:
为什么来自文档
在具有相同标签名称的元素之间切换时,您必须通过赋予它们唯一的键属性来告诉 Vue 它们是不同的元素.否则,Vue 的编译器为了效率只会替换元素的内容.即使在技术上没有必要,始终在一个组件中键入多个项也被认为是一种很好的做法.
HTML
<transition name="淡入淡出"><div key="1" v-if="!show"><div class="box blue"></div>
工作小提琴:https://jsfiddle.net/k6grqLh1/21/
已编辑
为了让它更流畅,你可以使用 Transition-Modes: mode="out-in"
,这将使当前元素先过渡出来,然后当完成时,新元素过渡进来.见下面的代码:
小提琴:https://jsfiddle.net/k6grqLh1/22/
I was trying to animated two divs using transition in Vuejs. Below is the code (jsfiddle) that I've used. But don't know why it's not working
https://jsfiddle.net/k6grqLh1/16/
vue
<div id="vue-instance">
<div>
<transition name="fade">
<div v-show="show">
<div class="box yellow"></div>
</div>
</transition>
<transition name="fade">
<div v-show="!show">
<div class="box blue"></div>
</div>
</transition>
<a href="#" @click="show = !show">Change</a>
</div>
</div>
css
.fade-enter-active, .fade-leave-active {
transition: opacity .5s
}
.fade-enter, .fade-leave-to /* .fade-leave-active in <2.1.8 */ {
opacity: 0
}
.box {
width:200px;height:200px;
}
.yellow{
background-color:yellow;
}
.blue{
background-color:blue;
}
js
var vm = new Vue({
el: '#vue-instance',
data: {
show: true
}
});
解决方案
You have to add key in each of the div, besides adding vue 2.x in the fiddle, You need to make following changes:
Why from docs
HTML
<transition name="fade">
<div key="3" v-if="show">
<div class="box yellow"></div>
</div>
</transition>
<transition name="fade">
<div key="1" v-if="!show">
<div class="box blue"></div>
</div>
</transition>
Working fiddle: https://jsfiddle.net/k6grqLh1/21/
Edited
To make it more smooth, you can use Transition-Modes: mode="out-in"
, which will make the current element transitions out first, then when complete, the new element transitions in. see below code:
<transition name="fade" mode="out-in">
<div key="3" v-if="show">
<div class="box yellow"></div>
</div>
<div key="1" v-if="!show">
<div class="box blue"></div>
</div>
</transition>
Fiddle: https://jsfiddle.net/k6grqLh1/22/
这篇关于在 VueJS 中平滑地为 v-show 设置动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!