标题定义Vue组件
什么是组件:组件的出现,就是为了拆分Vue实例的代码量的,能够让我们以不同的组件,来划分不同功能模块,将我们需要什么样的功能,就可以对调用对应的组件即可。
组件化和模块化的不同:
- 模块化:是从代码逻辑的角度进行划分的;方便代码的的分层开发,保证每个功能的职能单一;
- 组件化:是从UI界面的角度进行划分的;前端的组件化,方便UI组件的重用。
创建组件的方式:
1.使用Vue.extend 来创建Vue组件
<div id="main">
<!-- 如果要使用组件,只需要将组件的名称用HTML的形式引入即可 -->
<my-com1></my-com1>
</div>
var com1 = Vue.extend({
template:'<h3>使用Vue.extend创建的组件</h3>' //通过template属性,指定了组件要展示的HTML结构
})
//使用Vue.component('组件名称',创建出来的组件模板对象)
Vue.component('myCom1',com1);
var vu = new Vue({
el:'#main'
})
2.直接使用Vue.component()
<div id="main">
<!-- 如果要使用组件,只需要将组件的名称用HTML的形式引入即可 -->
<my-com1></my-com1>
</div>
Vue.component('myCom1',{
template:'<span>直接使用component创建组件</span>'
})
var vu = new Vue({
el:'#main'
})
3.通过 template 元素,在外部定义组件结构
<div id="threeIdea">
<com></com>
</div>
<template id="three">
<div>
<p>通过 template 元素,在外部定义组件结构</p>
<p>最好用的一种方式</p>
</div>
</template>
Vue.component('com',{
template:'#three'
})
var vmm = new Vue({
el:'#threeIdea',
})
注意: 不论是哪种方式创建出来的组件,组建的 template 属性指向的模板内容,必须有且只能有唯一的一个根元素。
定义一个私有组件:
<div id="self">
<comself></comself>
</div>
var selfa = new Vue({
el:'#self',
data:{},
components:{
comself: {
template:'<h2>这是一个私有组件</h2>'
}
}
})