什么是组件?
组件是vue.js最强大的功能之一。它能够扩展HTML元素,封装可重用的代码。在更高的层次上,组件是自定义的元素,vue的编译器给它添加特殊功能。其实在有些状况下,组件也能够是原生HTML元素的形式。用is特性扩展。html
注册 要注册一个全局组件,你能够使用 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 } })