vue2.0---组件

什么是组件?
组件是vue.js最强大的功能之一。它可以扩展HTML元素,封装可重用的代码。在更高的层次上,组件是自定义的元素,vue的编译器给它添加特殊功能。其实在有些情况下,组件也可以是原生HTML元素的形式。用is特性扩展。

注册

要注册一个全局组件,你可以使用 Vue.component(tagName, options)。 例如:
       Vue.component('my-component', {
          // 选项
        })

对于自定义标签名,Vue.js 不强制要求遵循 W3C规则 (小写,并且包含一个短杠),尽管遵循这个规则比较好。

组件在注册之后,便可以在父实例的模块中以自定义元素 <my-component></my-component> 的形式使用。要确保在初始化根实例之前 注册了组件:
//html
    <div id="example">
      <my-component></my-component>
    </div>
// 注册
    Vue.component('my-component', {
      template: '<div>这是一个自定义的组件</div>'
    })
// 创建根实例
    new Vue({
      el: '#example'
    })
 渲染为:
    <div id="example">
      <div>这是一个自定义的组件!</div>
    </div>


  局部注册

 不必在全局中注册每一个组件,通过使用组件实例选项注册,可以使组件仅在一个实例或者组件的作用域中使用。

    var child = {
        template :'<div>这是一个局部组件</div>'
    }

    new Vue({
        //....
        components:{
            //my-component这个组件只在父模板可以使用
            'my-component':child
        }
    })
posted @ 2017-01-05 11:54  L迷鹿L  阅读(175)  评论(0编辑  收藏  举报