更多关于Vue.js的系列文章请点击:Vue.js开发实践(0)-目录页
一、组件是什么
组件(Component)是 Vue.js 最强大的功能之一。
组件可以扩展 HTML 元素,封装可重用的代码。
组件系统让我们可以用独立可复用的小组件来构建大型应用,几乎任意类型的应用的界面都可以抽象为一个组件树:
二、注册全局组件
所有实例都能用全局组件。
<div id="app">
<hello></hello>
</div>
<script>
// 注册
Vue.component('hello', {
template: '<h1>自定义组件!</h1>'
})
// 创建根实例
new Vue({
el: '#app'
})
</script>
三、注册局部组件
我们也可以在实例选项中注册局部组件,这样组件只能在这个实例中使用:
<div id="app">
<runoob></runoob>
</div>
<script>
var Child = {
template: '<h1>自定义组件!</h1>'
}
// 创建根实例
new Vue({
el: '#app',
components: {
// <hello> 将只在父模板可用
'hello': Child
}
})
</script>
四、在components文件夹中创建组件文件
如果组件多的情况下,写在一个js文件里显然不方便管理,所以我们需要在src目录下创建一个components文件夹,用以存储组件。
- componentA.vue 存放在组件文件夹中
<template>
<div>
<h1>Hello ComponentA {{message}}</h1>
</div>
</template>
<script type="text/javascript">
export default {
data () {
return {
message: 'Welcome to Your Vue.js App'
}
}
}
</script>
<style>
</style>
每一个组件几乎都会含有这三个部分,它们分别是:< template >、< script >、< style >,它们的作用分别是
- 定义组件所含有的html模板
- 定义组件的行为
- 定义组件的样式
创建完组件后,我们可以在main.js中 引入它们,然后就可以正常地在实例中注册组件了:
- main.js
import Vue from 'vue'
import App from './App'
import componenta from './components/componentA'
Vue.config.productionTip = false
new Vue({
el: '#helloworld',
components: {
componenta
}
})
- index.html
<div id='helloworld'>
<componenta></componenta>
</div>