组件化
- 组件化是当今最为流行的一种可复用性增加的方法,随着当今前端开发的复杂度更加,这个组件化变得越来越流行
组件的特点及其使用方法
- Vue.js通过Vue.extend() 方法来扩展 组件的 使用
- Vue.extend( options ) 里面的options参数和 Vue(options) 的options参数几乎是一致的
- new Vue出来的 ViewModel( 视图模型 ) 也是一个组件,我们称之为 ‘根实例组件’ ,叫 ‘Root’ 组件
- Vue中组件的表现形式是类似于标签的,要想像标签一样使用,就必须得符合 h5 的规则,也就是必须要进行组件的注册
- 组件的注册有两种形式
- 全局注册
格式: Vue.component(组件的名称,组件的配置项)
组件的命名规则
举例:
1. Father Hello
2. my-button
- 局部注册
格式:
写在组件内注册
举例:
javascript new Vue({ componens: { 组件名: 组件配置项 } })
- 组件必须先注册在使用
- 组件中的模板需要使用一个叫做template的配置项表示
- 组件的配置项可以简写,不需要使用 Vue.extend(options),可以直接将options写在组件的注册中
- template组件中有且仅有一个根元素
具体步骤如下:
const Hello = Vue.extend({
template: '<div>虚怀若骨,戒骄戒躁</div>'
})
Vue.component( 'Word',Hello)
Vue.component('Like',{
template:'<h3>谦谦君子,婉婉有仪。</h3>'
})
new Vue({
el: '#app',
components:{
'Show':{
template: '#show'
}
}
})
<div id="app">
<Word></Word>
<Like></Like>
<template id="show">
<div>
<h4>局部注册标签写在app外面</h4>
</div>
</template>
</div>
- 组件使用时有规则的:
- 比如特殊的一些标签:
- 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>
<tr is = "Hello"></tr>
</table>
- 组件嵌套
全局注册:
要将子组件的组件名写在父组件的template中
局部注册<div id="app">
<Fater></Fater>
<table>
<tr>
<td>临</td>
<td>兵</td>
<td>斗</td>
</tr>
<tr is = "Hello"></tr>
</table>
</div>
<template id="hello">
<tr>
<td>者</td>
<td>皆</td>
<td>阵</td>
</tr>
</template>
<template id="fater">
<div>
<h4>Fater</h4>
<Son></Son>
</div>
</template>
<template id="son">
<h3>Son</h3>
</template>
---上面为全局注册嵌套,以下为局部嵌套
<template id="you">
<div>
<h4>You翩若惊鸿</h4>
<Must></Must>
</div>
</template>
<template id="must">
<h5>婉若游龙</h5>
</template>
Vue.component('Fater',{
template:'#fater'
})
Vue.component('Son',{
template:'#son'
})
------上面为全局注册嵌套,下面为局部注册嵌套
new Vue({
el: '#app',
components:{
'Hello':{
template: '#hello'
},
'You': {
template: '#you',
components:{
'Must':{
template:'#must'
}
}
}
}
})