Vue中的component
-
指令 – 用来操作dom
-
组件 – 组件是html css js 等的一个聚合体
-
组件化
- 将一个具备完整功能的项目的一部分进行多处使用
- 加快项目的进度
- 可以进行项目的复用
-
要想实现组件化,那么我们使用的这一部分就必须是完整的,我们把这个完整的整体就称之为组件
-
插件: index.html img css js
-
如果能将 html css js img 等多个部分放在一起,那该有多好,vue将这个聚合体的文件称之为,单文件组件( xx.vue )
-
-
基础的组件创建
1. 全局注册
Vue.component( 组件的名称,组件的配置项 ) 组件必须先注册在使用( 实例(组件) 范围内使用 ) <body> <div id="app"> <Father></Father> </div> <div id="root"> <Father></Father> </div> </body> <script> var Hello = Vue.extend({ template: '<div> 这是组件 </div>' }) Vue.component( 'Father', Hello ) 全局简写: Vue.component('Father',{ template: '<div> 这里是全局注册 </div>' }) new Vue({ el: '#app' }) new Vue({ el: '#root' }) </script>
2. 局部注册
在组件中用一个components的配置项目来表示 只能在注册的范围内使用,其他地方是不能使用的 命名: 一个单词的大写: 注意不要和原生的h5标签重名,比如 header footer Header Footer 小写带- , 比如 header-title 大驼峰: GabrielYan 使用 : gabriel-yan <script> var Hello = Vue.extend({ template: '<div> 这是组件 </div>' }) new Vue({ el: '#app', components: { // key: value key是组件名称 value是组件配置项 'gabriel-yan': Hello, 'GabrielYan': Hello } }) 局部组件 简写: components: { 'GabrielYan': { template: '<div> 这里是局部注册 </div>' } } </script>
-
组件的一些特殊使用规则 【 is 规则】
is规则
ul>li ol>li table>tr>td select>option
如上直属父子级如果直接组件以标签化形式使用,那么就会出现bug
解决: 使用is规则: 通过is属性来绑定一个组件
<body>
<div id="app">
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr is = "Hello"></tr>
</table>
</div>
</body>
Vue.component('Hello',{
template: '<tr> <td> 4 </td> <td> 5 </td><td> 6 </td> </tr>'
})
new Vue({
el: '#app'
})
-
组件的template
template使用:
-
实例范围内使用
template中的内容被当做一个整体了,并且template标签是不会解析 到html结构中的
-
实例范围外使用
实例范围外template标签是不会被直接解析的
组件要想使用template使用,我们采用第二种
但是使用第二种template使用后,有个弊端,template标签结构会在html文件中显示
<body> <div id="app"> <h3> 实例范围内使用 </h3> <template> <div> <ul> <li>1</li> <li>2</li> <li>3</li> </ul> </div> </template> <h3> 使用 hello 组件</h3> <Hello></Hello> </div> <h3> 实例范围外使用 </h3> <template id="hello"> <div> <ul> <li>1</li> <li>2</li> </ul> </div> </template> </body> <script> Vue.component('Hello',{ template: '#hello' }) new Vue({ el: '#app' }) </script>
-