组件说明
- Vuejs通过Vue.extend(options) 方法来扩展组件的使用
- options参数和 Vue(options) 的options参数几乎是一致的
- new Vue出来的 ViewModel( 视图模型 ) 也是一个组件,我们称之为 ‘根实例组件’ ,叫 ‘Root’ 组件
- Vue中组件的表现形式是类似于标签的,要想像标签一样使用,就必须得符合 h5 的规则,也就是必须要进行组件的注册
- 组件的注册有两种形式:全局注册 和 局部注册
全局注册
-
格式:
Vue.component(组件的名称,组件的配置项) -
命名规则:
1)Hello
2)my-button -
使用:
//1. 组件的配置项
const Hello = Vue.extend({
//组件中的模板需要使用一个叫做template的配置项来表示
template: '<div> Hello component!!! </div>'
})
// 2. 组件的注册
Vue.component( 'Hello', Hello )
//上面两步可以合并成一步
Vue.component('Hello',{
template: '<div> Hello component!!! </div>'
})
//组件必须先注册再使用(一定要先第二步再第三步)
// 3. 组件的使用
new Vue({
el: '#app'
})
局部注册(在根实例配置项的components中进行注册)
new Vue({
el: '#app',
components: {
'Hello': {
template: `
<h3> hello 局部注册
<p> 1902 </p> </h3>
`
}
}
})
template模板分离
component中template的html代码分离到html中,使用template标签+id实现挂载
<template id="hello">
<div>
<h3> hello 预祝端午节happy </h3>
</div>
</template>
- template标签下的标签只能有一个(
template组件中有且仅有一个根元素)
new Vue({
el: '#app',
components: {
'Hello': {
template: '#hello'
}
}
})
组件使用时的直接子元素规则
- 一些html标签直接规定了直接子元素:如:ul li ol li table tr td dl dt dd select option
- 将组件直接写入时会出现问题
- 解决:在直接子元素身上通过 is 属性来绑定 组件
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<!-- <Hello></Hello> 这么写有问题-->
<tr is = "Hello"></tr>
</table>
组件的嵌套
<div id="app">
<Father></Father>
</div>
<template id="father">
<div>
<h3> father </h3>
<hr>
<Son></Son>
</div>
</template>
<template id="son">
<h3> son </h3>
</template>
全局
Vue.component('Father',{
template: '#father'
})
Vue.component('Son',{
template: '#son'
})
new Vue({
el: '#app',
})
局部
new Vue({
el: '#app',
components: {
'Father': {
template: '#father',
components: {
'Son': {
template: '#son'
}
}
}
}
})