组件
-
- Vue.js通过Vue.extend() 方法来扩展 组件的 使用
Vue.extend()
-
Vue.extend( options ) 里面的options参数和 Vue(options) 的options参数几乎是一致的
-
new Vue出来的 ViewModel( 视图模型 ) 也是一个组件,我们称之为 ‘根实例组件’ ,叫 ‘Root’ 组件
-
Vue中组件的表现形式是类似于标签的,要想像标签一样使用,就必须得符合 h5 的规则,也就是必须要进行组件的注册
-
组件的注册有两种形式
全局注册- 格式: Vue.component(组件的名称,组件的配置项)
- 组件的命名规则
- 举例:
- Father Hello
- my-button
- 举例:
局部注册
- 格式:
- 写在组件内注册,举例:
new Vue({
componens: {
组件名: 组件配置项
}
})
- 组件必须先注册在使用
全局注册
const Myhtml = Vue.extend({
template: '<div>hello word</div>'
})
Vue.component('word', Myhtml)
// 简写
// 组件的配置项可以简写,不需要使用 Vue.extend(options),可以直接将options写在组件的注册中
Vue.component( 'Aa',{
template: '<h3> AA </h3>'
})
局部注册
// 必须要在根组件中使用
new Vue({
el: '#root',
components: {//在components中进行组件的注册
'Yh': {
template: '#yh'
}
})
- 组件中的模板需要使用一个叫做template的配置项表示
<template>
<!-- template中只能切只能有一个根节点 -->
<div>
<!-- 内容 -->
</div>
</template>
- 组件使用时有规则的:
比如特殊的一些标签:
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>
<!-- 在直接子元素身上,通过 is 属性来 绑定 一个组件 -->
</table>
- 组件嵌套
- 全局注册:
要将子组件的组件名写在父组件的template中
- 全局注册:
<template id="father_qj">
<div>
<son_qj></son_qj>
<h6>father_qj</h6>
</div>
</template>
<template id="son_qj">
<div>
<a href="#">son_qj</a>
</div>
</template>
- 局部注册
components: {
'Father_jb': {
template: '#father_jb',
components: {//要嵌套的写在这 在父组件之中
'Son_jb': {
template: "#son_jb"
}
}
}
}
插槽
作用: 可以让我们在组件中书写内容
- 通过slot方法预留出插槽
<template id="hello">
<div>
<slot></slot><!-- 预留出插槽 -->
</div>
</template>
- 具名插槽
<div id="app">
<Hello>
<header slot = "header"> 头部 </header>
</Hello>
</div>
<template id="hello">
<div>
<slot name = "header"></slot>
</div>
</template>
###动态组件:
-
动态组件是vue内部提供了一个叫做component的组件,这个组件身上可以通过绑定is属性来进行 组件的切换
-
keep-alive组件可以进行组件的内容缓存,将组件的内容存入浏览器缓存中,这样可以大大的节省街切换的事件
-
keep-alive 和 component动态组件两者常常一起搭配使用
<keep-alive include="">
<component :is = "name"></component>
</keep-alive>
// 动态组件:
// 动态组件是vue内部提供了一个叫做component的组件,这个组件身上可以通过绑定is属性来进行 组件的切换