美文网首页测试员的那点事
零基础学vue-动态组件

零基础学vue-动态组件

作者: 望月成三人 | 来源:发表于2020-11-01 19:36 被阅读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>

总结

  • 组件里面把内容写死,不推荐使用;template:"<h3>个人内容</h3>"
  • 使用<script type="text/x-template" id="index">的方式编写组件内容,比第一种好点,但是也不常用
  • 最优的解决方案就是用脚手架vue文件来解
  • 之前学习的方式,运行起来很慢,要经过首先解析组件内容,然后生成dom,然后把内容渲染到页面,这三步耗时略长,内容多的情况下,甚至出现白屏,而用vue脚手架就会在js中自动编译好,然后直接渲染
  • 用vue脚手架的优点,自动编译,自动压缩,错误检查,框架化程序等,都是用node来编写的,从下篇文章开始学习使用vue脚手架

相关文章

网友评论

    本文标题:零基础学vue-动态组件

    本文链接:https://www.haomeiwen.com/subject/slsuvktx.html