-
Notifications
You must be signed in to change notification settings - Fork 6
Open
Labels
Description
什么是组件
组件(Component)是 Vue.js 最强大的功能之一。组件可以扩展 HTML 元素,封装可重用的代码。在较高层面上,组件是自定义元素, Vue.js 的编译器为它添加特殊功能。在有些情况下,组件也可以是原生 HTML 元素的形式,以 is 特性扩展。
子组件中的数据源一般有父组件赋予,子组件中的事件也建议传递给父组件,由父组件执行对应的业务及逻辑
一、注册全局组件
Vue.component('componentName', {
// 选项
})
全局组件的简单使用方式
<div id="example">
<my-component></my-component>
</div>
// 初始化组件
// 注册
Vue.component('my-component', {
template: '<div>A custom component!</div>'
})
// 创建根实例
new Vue({
el: '#example'
})
得到
<div id="example">
<div>A custom component!</div>
</div>
二、注册局部组件
new Vue({
// ...
components: {
// <my-component> 将只在父模板可用
'my-component': {
template: '<div>A custom component!</div>'
}
}
});
三、DOM模板解析说明
如果按下面这样写,模板元素会跑到外面,自定义组件 被认为是无效的内容,因此在渲染的时候会导致错误。
<table>
<my-row>...</my-row>
</table>
用is改写
<table>
<tr is="my-row"></tr>
</table>
四、组件data必须是函数
要点便是使每一个组件都拥有自己的闭包体,使每一个按钮之间的数据相互独立。