vue组件

组件的使用共分为3个步骤:1.创建组件构造器、2.注册组件、3.使用组件。

一、全局组件

 <div id="app1">
        <my-component></my-component>
        
    </div>
    <div id="app2">
        <my-component></my-component>
    </div>
     <my-component></my-component>
    <script>
       //first:creat a 组件构造器
        var myComponent=Vue.extend({
            template:'<div>This is my first component!</div>'
        })
         //2.注册组件,并制定组件的标签,组件的HTML标签为,<my-component>
             Vue.component('my-component',myComponent)

        var app1=new Vue({
            el:'#app1'
        });
        var app2=new Vue({
            el:'#app2'
        })
    </script>

二、局部组件

<body>
   <div id="app">
        <my-component></my-component>
   </div>
</body>
<script>
    var myComponent=Vue.extend({
        template:'<div>This is my first component!</div>'
    })

    new Vue({
       el:'#app',
       components:{

           'my-component':myComponent  //这个标签下是局部的,那别的vue实例下就不能用
       }
    });
</script>

三、父子关系

<body>
   <div id="app">
         <parent-component></parent-component>
   </div>
</body>
<script>
   //父子关系
 
    // 先构造子元素
    var Child=Vue.extend({
        template:'<i>This is a Child!</i>'
    })

      // 子级注册都是在父级构造的里面,
    var Parent=Vue.extend({
        template:'<span>This is Parent!</span><child-component></child-component>',
        components:{
            'child-component':Child
        }
    })
       
    Vue.component('parent-component',Parent)
    new Vue({
        el:'#app'
    })
</script>

四、组件构造器直接在组件注册中实现

Vue.component('parent-component',{
    template:'<div>This is the first component!'
 })
  new Vue({
      el:'#app'
  })

五、在components中实现局部注册

var vm2 = new Vue({
    el: '#app2',
    components: {
        // 局部注册,my-component2是标签名称
        'my-component2': {
            template: '<div>This is the second component!</div>'
        },
        // 局部注册,my-component3是标签名称
        'my-component3': {
            template: '<div>This is the third component!</div>'
        }
    }
})

参考地址:http://www.cnblogs.com/keepfool/p/5625583.html

 

posted @ 2016-12-30 15:34  十二分努力  阅读(205)  评论(0编辑  收藏  举报