Vue多元素过渡

2019-10-13  本文已影响0人  手指乐
<style>
.fade-enter,.fade-leave-to{opacity:0;}
.fade-enter-active,.fade-leave-active{transition:opacity .5s;}
</style>
<div id="demo">
  <button @click="clear">清空数据</button>  
  <button @click="reset">重置</button>   
  <transition name="fade">
    <ul v-if="items.length > 0">
      <li v-for="item in items">{{item}}</li>
    </ul>
    <p v-else>Sorry, no items found.</p>
  </transition>
</div>
<script>
new Vue({
  el: '#demo',
  data: {
    items: ['html','css','js']
  },
  methods:{
    clear(){
      this.items.splice(0);
    },
    reset(){
      history.go();
    }
  }
})
</script>

清空列表的时候,列表逐渐消失,同时文字逐渐出现,文字先放在列表后面,列表0.5s后完全消失,文字瞬间上移到列表之前的位置

<div id="demo">
  <button @click="show = !show">toggle</button>   
  <transition name="fade">
    <p v-if="show">我是小火柴</p>
    <p v-else>我不是小火柴</p>
  </transition>
</div>


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

这样切换不会有任何过渡,可以通过绑定一个key来区分相同的标签解决这个问题

<div id="demo">
  <button @click="show = !show">toggle</button>   
  <transition name="fade">
    <p v-if="show" key="trueMatch">我是小火柴</p>
    <p v-else key="falseMatch">我不是小火柴</p>
  </transition>
</div>
<transition>
  <button v-if="isEditing" key="save">Save</button>
  <button v-else key="edit">Edit</button>
</transition>
<transition>
  <button v-bind:key="isEditing">
    {{ isEditing ? 'Save' : 'Edit' }}
  </button>
</transition>

过渡的时候,它们两个效果一样

  1. in-out: 新元素先进行过渡,完成之后当前元素过渡离开。
  2. out-in: 当前元素先进行过渡,完成之后新元素过渡进入。
<div id="demo">   
  <transition name="fade"  mode="out-in">
    <button :key="isOn" @click="isOn = !isOn">{{ isOn ? 'On' : 'Off' }}</button>
  </transition>
</div>
<style>
#demo{position:relative;}
#demo button{position:absolute;left:40px;}
.fade-enter,.fade-leave-to{opacity:0;}
.fade-enter-active,.fade-leave-active{transition: 1s;}
</style>

<div id="demo">   
  <transition name="fade"  >
    <button :key="isOn" @click="isOn = !isOn">{{ isOn ? 'On' : 'Off' }}</button>
  </transition>
</div>
<div id="demo">   
  <transition name="fade"  >
    <button :key="isOn" @click="isOn = !isOn">{{ isOn ? 'On' : 'Off' }}</button>
  </transition>
</div>

<div id="example">
  <button @click="change">切换页面</button>
  <transition name="fade" mode="out-in">
    <component :is="currentView"></component>
  </transition>
</div>

<script>
new Vue({
  el: '#example',
  data:{
    index:0,
    arr:[
      {template:`<div>ComponentA</div>`},
      {template:`<div>ComponentB</div>`},
      {template:`<div>ComponentC</div>`}
    ],
  },
  computed:{
    currentView(){
        return this.arr[this.index];
    }
  },
  methods:{
    change(){
      this.index = (++this.index)%3;
    }
  }
})
</script>
上一篇下一篇

猜你喜欢

热点阅读