How can I use transition on individual list elements in Vue.js?

烂漫一生 提交于 2021-01-28 14:45:21

问题


My understanding of transitions in vue.js is that you use <transition> to animate between individual elements and <transition-group> to animate a whole list.

It seems as though if you wanted to animate a transition within a list item you'd use <transition> within the list. e.g. something like this:

<span v-for="item in items">
  <transition>

    <div>
        Transition from this...
    </div>

    <div>
         ...to this.
    </div>

  </transition>
</span>

Yet, when I make that change the animation doesn't work. Is this an expected behavior?

Update: after some tinkering, I have found that my original hypothesis was correct. I was just doing something else wrong. But it's worth noting for anyone else who comes across this problem.

You can use <transition> inside a list if you want to animate individual components of the list.


回答1:


You use transition groups to transition all children in the same way. In addition, try setting the transition group before your v-for

new Vue({
  el: "#app",
  data: {
    items : [
      {message: 'sometext', id: 1},
      {message: 'sometext', id: 2},
      {message: 'sometext', id: 3}
     ],
     id : 3
  },
  methods: {
  	 addItem(){
            this.id++
            this.items.push({message: 'sometext', id: this.id});
        },
     enter(){
         console.log('transition enter called');
     }
  }
})
.fade-enter-active, .fade-leave-active {
  transition: opacity .5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div id="container">
        <button @click="addItem()">Add Item</button>
        <transition-group :name="'fade'" v-on:enter="enter">
            <span v-for="item in items" v-bind:key="item.id">
               {{item.message}}
            </span>
        </transition-group>
    </div>
</div>



回答2:


I am not exactly sure what you are trying to do with your example.

If you would like to transition a list

  <transition-group name="fade" tag="span">
    <div v-for="item in items" v-bind:key="item">
      {{ item }}
    </div>
  </transition-group>

If you would like to transition between two items.

  <transition name="fade">
    <div v-show="whatever === true">
      Transition from this...
    </div>
  </transition>
  <transition name="fade">
    <div v-show="whatever === false">
     ...to this.
    </div>
  </transition>


来源:https://stackoverflow.com/questions/54062930/how-can-i-use-transition-on-individual-list-elements-in-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!