首页 Vue.js正文

Vue.js源码分析(三十一)高级应用keep-alive组件详解

Vue.js 2019-11-16 14:11:40 635

当使用is特性切换不同的组件时,每次都会重新生成组件Vue实例并生成对应的VNode进行渲染,这样是比较花费性能的,而且切换重新显示时数据又会初始化,例如:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
</head>
<body>

    <div id="app">
        <button @click="currentComp=currentComp=='A'?'B':'A'">切换</button>               <!--动态组件-->
        <component :is="currentComp"/>
    </div>
    <script>
        with(Vue.config){productionTip=false;devtools=false;}
        var app  = new Vue({
            el: '#app',
            components:{
                A:{
                    template:"<div><input type='text'/></div>",
                    name:'A',
                    mounted:function(){console.log('Comp A mounted');}
                },
                B:{
                    template:"<div>B组件</div>",
                    name:'B',
                    mounted:function(){console.log('Comp B mounted');}
                }
            },
            data:{
                currentComp:"A"
            }
        })
    </script>

</body>
</html>
© 编程脚本学习网