Vue CSS 动画原理

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <script src="./vue.v2.6.10.dev.js"></script>
    </head>
    <body>
        <div id="app">
            <div v-if="show">Hello World</div>
            <button @click="handleClick">切换</button>
        </div>
        
        <script>
            
            var vm = new Vue({
                el: '#app', 
                data: {
                    show: true,
                },
                methods: {
                    handleClick: function() {
                        this.show = !this.show
                    }
                }
            })
        </script>
    </body>
</html>

为上面的切换实现一个效果。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <script src="./vue.v2.6.10.dev.js"></script>
        <style>
            .fade-enter {
                opacity: 0;
            }
            .fade-enter-active {
                transition: opacity 3s;
            }
            .fade-leave-to {
                opacity: 0;
            }
            .fade-leave-active {
                transition: opacity 3s;
            }
        </style>
    </head>
    <body>
        <div id="app">
            <transition name="fade">
                <div v-if="show">Hello 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>
    </body>
</html>

动画目标通过 transition 标签包裹起来,在动画的过程当中赋予一些类名字:

v-enter
v-enter-active
v-enter-to

v-leave
v-leave-active
v-leave-to

在动画开始的时候,动画进入显示,第一帧将会运行

v-enter
v-enter-active

而第二帧的时候,v-enter 被删除,于此同时,v-enter-to 将被激活。

到了最后一帧完结后,

v-enter-active
v-enter-to

将被删除。

当动画进入隐藏的时候也是类似的过程。

transition 标签上定义一个名字:

<transition name="fade"></transition>

就可以把默认的动画类改成那个名字的前缀了:

.fade-enter {
    opacity: 0;
}
.fade-enter-active {
    transition: opacity 3s;
}
.fade-leave-to {
    opacity: 0;
}
.fade-leave-active {
    transition: opacity 3s;
}