测试员的那点事

零基础学vue-动态组件

2020-11-01  本文已影响0人  望月成三人
<html>
    <head>
        <meta charset="utf-8">
        <title>动态组件</title>
        <script type="text/javascript" src="js/vue.js"></script>
    </head>
    <body>
        <div id="app">
            <div id="content">
                <!-- is动态获取组件名 -->
                <component :is="com"></component>
            </div>
            <!-- 方法动态设置组件名 -->
            <button @click="chooseComponent(1)">首页</button>
            <button @click="chooseComponent(2)">列表</button>
            <button @click="chooseComponent(3)">新闻</button>
            <button @click="chooseComponent(4)">我的</button>
        </div>
        <script type="text/x-template" id="index">
            <div>
                <h3>首页内容</h3>
                <p>首页内容</p>
            </div>
        </script>
        <script type="text/javascript">
            let com1 = Vue.component("index-com", {
                name:"index",
                // 调用   <script type="text/x-template" id="index">的内容
                template:"#index"
            })
            let com2 = Vue.component("list-com", {
                name:"list",
                template:"<h3>列表内容</h3>"
            })
            let com3 = Vue.component("new-com", {
                name:"new",
                template:"<h3>新闻内容</h3>"
            })
            let com4 = Vue.component("me-com", {
                name:"me",
                template:"<h3>个人内容</h3>"
            })
            
            let app = new Vue({
                el: "#app",
                data: {
                    com:com1
                },
                methods:{
                    chooseComponent:function(id){
                        console.log(this) // 打印发现option下出现了4个组件
                        this.com = this.$options.components['com'+id]
                    }
                },
                // 注册组件
                components:{
                    com1,com2,com3,com4
                }
            })
        </script>
    </body>
    
</html>

总结

上一篇下一篇

猜你喜欢

热点阅读