根据Vue官方文档:组件(Component)是Vue.js最强大的功能之一。组件可以扩展HTML元素,封装可重用的代码。在较高层面上,组件是自定义元素。
按我当前学习程度的理解,组件就是定义一个自己的新标签,新标签可以在HTML代码中使用。
全局声明组件
Vue.component('my-component-button1', { template: '<button>myFirstComponent</button>' }); var app1 = new Vue( el: '#app1' //绑定DOM元素 );
局部声明组件,局部声明的组件则只能让注册该组件的Vue实例使用。
var localComponent = { template: '<button>myFirstLocalComponent</button>' } var app2 = new Vue({ el: '#app2' //绑定DOM元素 //注意↓有s components: { 'my-component-button2': localComponent } })
HTML:
<!-- 第一个全局按钮组件 --> <div id="app1"> <my-component-button1></my-component-button1> </div> <!-- 第一个局部按钮组件,只能让app2用,因为只用app2注册了.--> <div id="app2"> <my-component-button2></my-component-button2> </div>
两个组件分别被渲染为:
<div id="app1"> <button>myFirstComponent</button> </div> <div id="app2"> <button>myFirstLocalComponent</button> </div>
需要注意:模板的名字最好不要用驼峰式命名(camelCase),使用短横线分隔式命名(kebab-case)。
#组件组合
来自Vue官方文档:
组件设计初衷就是要配合使用的,最常见的就是形成父子组件的关系:组件 A 在它的模板中使用了组件 B。它们之间必然需要相互通信:父组件可能要给子组件下发数据,子组件则可能要将它内部发生的事情告知父组件。然而,通过一个良好定义的接口来尽可能将父子组件解耦也是很重要的。这保证了每个组件的代码可以在相对隔离的环境中书写和理解,从而提高了其可维护性和复用性。
在 Vue 中,父子组件的关系可以总结为 prop 向下传递,事件向上传递。父组件通过 prop给子组件下发数据,子组件通过事件给父组件发送消息。下一篇继续学习prop和emit,看看它们是怎么工作的。