1. 程式人生 > >Vue元件--動態元件

Vue元件--動態元件

所謂的動態元件,就是利用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是不變的,因為已經被快取了下來 -->