vue中组件的过渡动画及实现代码

1.  和多个元素的过渡一样,用组件来替换transition中包裹的标签

<style>
 .fade-enter,
 .fade-leave-to {
  opacity: 0
 }
 .fade-enter-active,
 .fade-leave-active {
  transition: opacity 2s
 }
 </style>
</head>

<body>
 <div id="demo">
 <button @click="show = !show">click me</button>
 <transition name="fade" mode="in-out">
  <child-one v-if="show"></child-one>
  <child-two v-else></child-two>
 </transition>
 </div>
 <script>
 Vue.component('child-one', {
  template: `<div>child-one</div>`
 })
 Vue.component('child-two', {
  template: `<div>child-two</div>`
 })
 new Vue({
  el: '#demo',
  data: {
  show: true
  },
 })
 </script>

2.  动态组件:component组件 :is 属性,来实现组件的过渡效果 

<style>
 .fade-enter,
 .fade-leave-to {
  opacity: 0
 }
 .fade-enter-active,
 .fade-leave-active {
  transition: opacity 2s
 }
 </style>
</head>

<body>
 <div id="demo">
 <button @click="handleClick">click me</button>
 <transition name="fade" mode="in-out">
  <component :is="type"></component>
 </transition>
 </div>
 <script>
 Vue.component('child-one', {
  template: `<div>child-one</div>`
 })
 Vue.component('child-two', {
  template: `<div>child-two</div>`
 })
 new Vue({
  el: '#demo',
  data: {
  type: 'child-one'
  },
  methods:{
  handleClick () {
   this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
  }
  }
 })
 </script>

PS:下面看下Vue过渡动画实现

实现一个点击切换元素的隐藏和显示状态!

<div id="app">
  <transition>
    <p v-if="show">Hello World</p>
  </transition>
  <button @click="toggle">切换</button>
</div>

需要把加入动画的元素放在transition组件内,定义一个按钮的切换方法

<script>
  var app=new Vue({
    el:"#app",
    data:{
      show:true
    },
    methods:{
      toggle:function(){
        this.show=!this.show;
      }
    }

  })
</script>

给不同状态下添加相应的样式

.v-enter,.v-leave-to{
  opacity:0;
}
.v-enter-active,.v-leave-to{
  color:#00BFFF;
  transition: opacity 3s;
}

可以给transition添加一个name,如果name为"fade",则class前缀为指定的name

动画过程中类名的变化

我们可以自定义类名,在元素属性中添加进入状态 enter-active-class,和离开状态leave-active-class

总结

以上所述是小编给大家介绍的vue中组件的过渡动画及实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对呐喊教程网站的支持!

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。