Vue 组件开发

 

将页面拆分为多个组件,简化了页面开发,方便维护,组件也可以复用。

 

组件的类型

  • 通用组件,比如表单、弹窗、菜单栏、分页组件等
  • 业务组件,实现某一业务的组件,比如抽奖组件
  • 页面组件,也叫做单页,一个页面就是一个组件,只完成功能,不复用

 

组件开发流程:声明、注册、使用

 

 

demo  组件使用流程

   <div id="app"></div>
    
    
    <script>

        var myHeader={  //声明一个组件
            template:'<div>this is the header area</div>'
        }
        
        var myBody={
            template:'<div>this is the body area</div>'
        }
        
        var myFooter={
            template:'<div>this is the footer area</div>'
        }
        
        new Vue({
            el:'#app',
            components:{  //注册组件
                myHeader,
                myBody,
                myFooter
            },
            template:'<div><myHeader></myHeader><myBody></myBody><myFooter></myFooter></div>' //使用组件
        });
        
    </script>

声明是全局声明,但需要在每一个使用Vue对象中进行注册。

 

 

使用组件有2种方式

  • <myHeader></myHeader>  直接以变量名作为标签名
  • <my-header></my-header>  单词都转换为全小写,-连接

 

 

声明组件时是用了语法糖的

    // 原来的写法
    var myHeader=Vue.extend({
        template:'<div>this is the header area</div>'
    })
    
    // 语法糖
    var myHeader={ 
        template:'<div>this is the header area</div>'
    }

效果都一样,但使用语法糖明显要简便些

 

 

 

组件声明、注册的另一种方式

  // 声明+注册一个组件
    Vue.component('MyHeader',{
        template:'<div>this is the header area</div>'
    })
    
    Vue.component('MyBody',{
        template:'<div>this is the body area</div>'
    })
    
    Vue.component('MyFooter',{
        template:'<div>this is the footer area</div>'
    })
        
    new Vue({
        el:'#app',
        template:'<div><my-header></my-header><my-body></my-body><my-footer></my-footer></div>' //使用组件
    });

声明、注册都是全局的,在Vue对象中可以直接使用

 

 

组件中除了template,还可以有其它部分,比如data。

 

posted @ 2020-04-01 13:51  chy_18883701161  阅读(494)  评论(0编辑  收藏  举报