今天开始复习组件的相关内容。
组件的概念
- 组件用于封装页面的部分功能,将功能的结构、样式、逻辑代码封装为整体
- 提高功能复用性与可维护性,更好的专注于业务逻辑
- 组件使用时为自定义HTML标签形式,通过组件名作为自定义标签名
组件注册
全局注册
- 全局注册的组件在注册后可以用于任意实例或组件中:
Vue.component('组件名',{选项对象});
- 注意:全局注册必须设置在根Vue实例创建之前
组件基础
- 本质上,组件是可复用的Vue实例,所以它们可与new Vue接收相同的选项,例如data、methods以及生命周期钩子等
- 仅有的例外是像el这样根实例特有的选项
组件命名规则
- kebab-case:‘my-component’
- PascalCase:‘MyComponent’
- 注意:无论采用哪种命名方式,在DOM中都只有kebab-case可以使用
template选项
- template选项用于设置组件的结构,最终被引入根实例或其他组件中
Vue.component('MyComponentA',{
template:`
<div>
<h3>组件A的标题</h3>
</div>`,
});
- 注意:组件必须只有一个根元素
data选项
- data选项用于存储组件的数据,与根实例不同,组件的data选项必须为函数,数据设置在返回值对象中
Vue.component('MyComponentA',{
template:`
< div>
< h3>{{title}}< /h3>
< /div>`,
data:function(){
return {
title:'示例内容'
}
}
});
- 这种实现方式是为了确保每个组件实例可以维护一份被返回对象的独立的拷贝,不会相互影响
局部注册
- 局部注册的组件只能用在当前实例或组件中
new Vue({
components:{
'my-component-a':{
template:`
< div>
< h3>组件A的标题< /h3>
< /div>`,
data(){
return {
title:'a的示例内容'
}}},
'my-component-b':{
template:`
< div>
< h3>组件B的标题< /h3>
< /div>`,
data(){
return {
title:'b的示例内容'
}}}
}});
- 单独配置组件的选项对象:
var MyComponentA = {/*...*/}
var MyComponentB = {/*...*/}
new Vue({
components:{
'my-component-a':MyComponentA,
'my-component-b':MyComponentB
}
});
- ES6的对象属性简写:
new Vue({
components:{
MyComponentA,
MyComponentB
}
});
ok,组件注册的部分复习完了,明天开始复习组件通信的内容,今日份推荐歌曲:周华健-有没有一首歌会让你想起我