简体   繁体   English

在 Vue 组件渲染上同时转换多个元素

[英]Transition multiple elements at the same time on Vue component render

Simple case shown in the following jsfiddle:以下jsfiddle中显示的简单案例:

https://jsfiddle.net/hsak2rdu/ https://jsfiddle.net/hsak2rdu/

I want to swap and animate two elements, but fail.我想交换和动画两个元素,但失败了。 As you can see after clicking the toggle button in the playground, the second element flashes into the final position.正如您在操场上单击切换按钮后看到的那样,第二个元素闪烁到最终的 position 中。

I want them both animated at the same time, like crossing each other.我希望它们同时具有动画效果,就像相互交叉一样。 Is it possible?可能吗?

Template:模板:

<div id="app">
  <div class="dom" v-for="(_d, _i) in list" :key="_d.id" :style="{ top: _i * 50 + 'px'}">
    <span>{{_d.text}}{{_i}}</span>
  </div>
  <button @click="handle">Toggle</button>
  {{list}}
</div>

JS: JS:

new Vue({
  el: '#app',
  data: {
    show: true,
    list: [
      {
        id:1,
        text:'First'
      },
      {
        id:2,
        text:'Second'
      }
    ]
  },
  methods:{
    handle: function (){
      console.log("DEBUG", this.list)
      let a = JSON.parse(JSON.stringify(this.list[0]));
      let b = JSON.parse(JSON.stringify(this.list[1]))
      this.$set(this.list, 0, b);
      this.$set(this.list, 1, a);
    }
  }
});

The only necessary change is to wrap the v-for in a <transition-group> :唯一必要的更改是将v-for包装在<transition-group>中:

<transition-group tag="div" name="list">
  <div class="dom" v-for="(_d, _i) in list" :key="_d.id" :style="{ top: _i * 20 + 'px' }">
    <span>{{_d.text}}{{_i}}</span>
  </div>
</transition-group>

From the docs :文档

This might seem like magic, but under the hood, Vue is using an animation technique called FLIP to smoothly transition elements from their old position to their new position using transforms这可能看起来很神奇,但在幕后,Vue 使用了一种称为FLIP的 animation 技术,使用转换将元素从旧的 position 平滑过渡到新的 position

Here's a demo:这是一个演示:

 new Vue({ el: '#app', data: () => ({ show: true, list: [ { id:1, text:'First' }, { id:2, text:'Second' } ] }), methods:{ handle: function (){ console.log("DEBUG", this.list) let a = JSON.parse(JSON.stringify(this.list[0])); let b = JSON.parse(JSON.stringify(this.list[1])) this.$set(this.list, 0, b); this.$set(this.list, 1, a); } } });
 .dom{ position: absolute; transition: all 1s linear; opacity: 1; } button{ margin-top: 50px; } #app{ margin-top: 50px; position: relative; }
 <div id="app"> <transition-group tag="div" name="list"> <div class="dom" v-for="(_d, _i) in list":key="_d.id":style="{ top: _i * 20 + 'px' }"> <span>{{_d.text}}{{_i}}</span> </div> </transition-group> <button @click="handle">Toggle</button> {{list}} </div> <script src="https://unpkg.com/vue/dist/vue.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM