Vue组件--动态组件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/codesWay/article/details/79487674

所谓的动态组件,就是利用Vue内置组件<component is = "">,来实现在同一个挂载点,多个组件的切换;在这里所谓的"同一个挂载点"就指的是<component is = "">组件本身,is的值时某一自定义组件的组件id例如:

JS部分:

var app = new Vue({
            el:"#container",
            data:{
                name:"Tom",
                flags:'my-world' //初始化时,指向组件id为my-world的组件    
            },
            methods:{//切换组件
                showMyWorld:function(){
                    this.flags = "my-world"
                },
                showMyCountry: function () {
                    this.flags = "my-country"
                }
            },
            components:{
                // 在这里my-hello是组件的id,并不是组件名,组件名要在自定义组件里通过name选项来定义,组件一
                "my-world":{
                    template:"<h2>{{weather}}hehe{{statusX}}</h2>",
                    data:function(){
                        return {
                            weather:"cloudy",
                            statusX:Math.random()
                        }
                    }
                },
                // 组件二,其他同上
                "my-country":{
                    template:"<h2>{{country}}haha{{statusY}}</h2>",
                    data:function(){
                        return {
                            country:"China",
                            statusY: Math.random()
                        }
                    }
                }
            }
        })

HTML部分

<!-- 初始化显示my-world组件 -->
        <component :is="flags"></component>
        <!-- component组件本身就是那个"挂载点" -->


在这里,初始化显示组件my-world,因为flag初始化的时候就是my-world,通过点击按钮来切换组件,

动态组件下的缓存问题:

在一般情况下,动态切换组建件的时候会动态的创建活动组件和销毁非活动的组件,并进行渲染,这样的话会对性能造成不利的影响。

Vue提供了一个解决方案来解决了这个问题:使用keep-alive组件缓存非活动的组件(就是被切换出去的组件),并保留其状态,避免重新渲染,

 使用方法是:用内置组件<keep-alive>来包裹住<component is = "">组件,例如:

<keep-alive>
            <component :is="flags"></component>
        </keep-alive>
        <!-- 每次切换回到原来的组件的时候statusY或者statusX是不变的,因为已经被缓存了下来 -->







猜你喜欢

转载自blog.csdn.net/codesWay/article/details/79487674