VUE3 之 多个组件之间的过渡 - 这个系列的教程通俗易懂,适合新手

1. 概述

老话说的好:多换位思考,多站在他人的角度考虑问题,多考虑他人的感受,这样才能让我们赢得更多的朋友。

 

言归正传,之前我们聊了多个元素之间的过渡,今天我们聊聊多个组件之间的过渡。

 

2. 多个组件之间的过渡

2.1 局部组件之间过渡的实现

    <style>
       /* 入场起始样式 */
       .v-enter-from {
            opacity: 0;
        }
        /* 入场过渡效果 */
        .v-enter-active {
            transition: 2s opacity ease-in; 
        }
        /* 入场结束样式 */
        .v-enter-to {
            opacity: 1;
        }

        /* 出场起始样式 */
        .v-leave-from {
            opacity: 1;
        }
        /* 出场过渡效果 */
        .v-leave-active {
            transition: 2s opacity ease-in; 
        }
        /* 出场结束样式 */
        .v-leave-to {
            opacity: 0;
        }
    </style>

 

<body>
    <div id="myDiv"></div>
</body>
<script>

    const ComponentOn = {
        template:`<div><h3>on</h3></div>`
    }

    const ComponentOff = {
        template:`<div><h3>off</h3></div>`
    }

    const app = Vue.createApp({
        data(){
            return {
                show : false
            }
        },
        methods : {
            myClick() {
                this.show = !this.show;
            }
        },
        components: {
            'component-on' : ComponentOn,
            'component-off' : ComponentOff
        },
        template:`
            <div class="center">
                <transition mode="out-in" appear>
                    <component-on v-if="show"/>
                    <component-off v-else="show" />
                </transition>
                <button @click="myClick">切换</button>
            </div>
        `
    });
    const vm = app.mount("#myDiv");

 

 这个例子中,我们新增了两个局部组件,然后在 transition 标签中,用组件代替之前的元素,我们会发现,效果和之前直接用元素没有区别。

 

2.2 动态组件方式实现过渡

    const app = Vue.createApp({
        data(){
            return {
                myComponent : 'component-off'
            }
        },
        methods : {
            myClick() {
                if(this.myComponent === 'component-off') {
                    this.myComponent = 'component-on';
                } else {
                    this.myComponent = 'component-off';
                }
            }
        },
        components: {
            'component-on' : ComponentOn,
            'component-off' : ComponentOff
        },
        template:`
            <div class="center">
                <transition mode="out-in" appear>
                    <component :is="myComponent" />
                </transition>
                <button @click="myClick">切换</button>
            </div>
        `

    });

这里我们使用了之前动态组件的知识,用 component 标签,替换了 v-if 的写法,效果也是一样的。

 

3. 综述

今天聊了一下 VUE3 中多个组件之间的过渡,希望可以对大家的工作有所帮助,下一节我们继续讲 Vue 中 动画 的相关知识,敬请期待

欢迎帮忙点赞、评论、转发、加关注 :)

关注追风人聊Java,这里干货满满,都是实战类技术文章,通俗易懂,轻松上手。

 

4. 个人公众号

追风人聊Java,欢迎大家关注

posted @ 2022-03-13 19:41  追风人聊Java  阅读(359)  评论(0编辑  收藏  举报