Vue 动态组件

时间:2021-08-22
本文章向大家介绍Vue 动态组件,主要包括Vue 动态组件使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
    </div>
    <script src="js/vue.3.2.2.js"></script>
    <script>
        // 1、创建Vue的实例对象
        const app = Vue.createApp({
            data(){//定义数据
                return {
                    msg:'你好!',
                    cItem:'btn_1'
                }
            },
            methods:{
                change(){
                    if(this.cItem==='btn_1'){
                        this.cItem='input_1';
                    }else if(this.cItem==='input_1'){
                        this.cItem='btn_1';
                    }
                }
            },
            template:'<h1>{{msg}}</h1>' +
                    '<div>' +
                    // '<btn_1 v-show="cItem==\'btn_1\'"></btn_1>' +
                    // '<input_1 v-show="cItem==\'input_1\'"></input_1>'+
                    '<keep-alive><component :is="cItem"></component></keep-alive>'+<!-- 动态组件component :is   保持缓存 keep-alive  -->
                    '<button @click="change">btn</button>'+
                    '</div>'
        });

        app.component('btn_1',{template: '<button>btn_1</button>'});
        app.component('input_1',{template:'<input type="text"/>'});

        app.mount('#app');
    </script>
</body>
</html>

原文地址:https://www.cnblogs.com/mingforyou/p/15173352.html