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