组件的概念
- 组件是一个html、css、js、image等外链资源,这些部分组成的一个聚合体。
- 优点:代码重复使用,便于维护。
- 组件化思维:组件化针对的是页面中的整个完整的功能模块划分。
Vue中的组件
- Vue.js通过Vue.extend() 方法来扩展组件的使用。
- Vue.extend(options)里面的options参数和Vue(options)的options参数几乎是一致的。
- new Vue出来的 ViewModel(视图模型)也是一个组件,我们称之为’根实例组件’叫’Root’组件。
- Vue中组件的表现形式是类似于标签的,要想像标签一样使用,就必须得符合h5的规则,也就是必须要进行组件的注册。
- 组件的注册有两种形式
- 全局注册
- 局部注册
- 组件必须先注册在使用。
组件注册
- 全局注册
- 格式: Vue.component(组件的名称,组件的配置项)
- 注册组件就是利用Vue.component()方法,先传入一个自定义组件的名字,然后传入这个组件的配置。
//1.组件的配置
const Hello = Vue.extend({
template: '<div>你是真的帅</div>'
});
//2.组件的注册
Vue.component('Hello', Hello);
//3.组件的使用
new Vue({
el: '#app'
})
<div id="app">
<Hello></Hello>
</div>
- 组件的配置项可以简写,不需要使用Vue.extend(options),可以直接将options写在组件的注册中。
Vue.component("Hello",{
template:'<p>我是简写形式</p>'
})
- 局部注册
- 局部注册只能在这个
- 格式:
// 写在组件内注册
new Vue({
components: {
组件名: 组件配置项
}
})
new Vue({
el: '#app',
components: {
'Hello': {
template: `<h2>我是局部组件</h2>`
}
}
})
template
- 组件中的模板需要使用一个叫做template的配置项表示。
- 可以在html中使用。如以下例子
<div id="app">
<template>
<h3>我是template</h3>
</template>
</div>
new Vue({
el:'#app',
components:{
"Hello":{
tamplate:'#hello'
}
}
})
- template组件中有且仅有一个根元素
<div id="app">
<template>
<div>//只有一个根元素
<div>34</div>
<h3>我是template</h3>
<p>dsfdsf</p>
</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>
<!-- <Hello></Hello> 这么写有问题-->
<tr is = "Hello"></tr>
</table>
组件的嵌套
-
- 全局注册:
要将子组件的组件名写在父组件的template中
<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'
}
}
}
}
})