首页 > 语言 > JavaScript > 正文

vue实现多个元素或多个组件之间动画效果

2024-05-06 15:29:33
字体:
来源:转载
供稿:网友

本文实例为大家分享了vue实现多个元素或多个组件之间动画的具体代码,供大家参考,具体内容如下

多个元素的过渡

<style>  .v-enter,.v-leave-to{    opacity: 0;  }  .v-enter-acitve,.v-leave-active{    opacity: opacity 1s;  }</style><div id='app'>  <transition>    <div v-if='show'>hello world</div>    <div v-else>bye world</div>  </transition>  <button @click='handleClick'>切换</button></div><script>var vm = new Vue({  el:'#app',  data:{    show:true  },  methods:{    handleClick:function(){      this.show = !this.show;    }  }})</script>

按照之前的写法方式,渐隐渐出的效果并没有出现该有的效果,那么为什么呢?

在if else两个元素切换的时候,会尽量的复用dom,正是vue,dom的复用,导致动画的效果不会出现,如果想要vue不去复用dom,之前也说过,怎么做呢,给两个div不同的key值就行了

<div v-if='show' key='hello'>hello world</div><div v-else key='bye'>bye world</div>

这样就可以有个明显的动画效果,多个元素过渡动画的效果。

transition还提供了一个mode属性,in-out是先显示再隐藏,out-in是先隐藏再显示

多个组件的过渡

<style>  .v-enter, .v-leave-to {    opacity: 0;  }  .v-enter-acitve, .v-leave-active {    transition: opacity 1s;  }</style><div id='app'>  <transition mode='out-in'>    <child v-if='show'></child>    <child-one v-else></child-one>  </transition>  <button @click='handleClick'>切换</button></div><script>Vue.component('child',{  template:'<div>child</div>'})Vue.component('child-one',{  template:'<div>child-one</div>'})var vm = new Vue({  el:'#app',  data:{    show:true  },  methods:{    handleClick:function(){      this.show = !this.show;    }  }})</script>

这个就是多个组件的过渡,采用的是上面的方式,替换子组件,那么我们换一种方式,用动态组件

<style>  .v-enter, .v-leave-to {    opacity: 0;  }  .v-enter-acitve, .v-leave-active {    transition: opacity 1s;  }</style><div id='app'>  <transition mode='out-in'>    <component :is='type'></component>  </transition>  <button @click='handleClick'>切换</button></div><script>Vue.component('child',{  template:'<div>child</div>'})Vue.component('child-one',{  template:'<div>child-one</div>'})var vm = new Vue({  el:'#app',  data:{    type:'child'  },  methods:{    handleClick:function(){      this.type = (this.type === 'child' ? 'child-one' : 'child')    }  }})</script>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选