组件介绍
组件系统是Vue.js其中一个重要的概念,它提供了一种抽象,让我们可以使用独立可复用的小组件来构建大型应用,任意类型的应用界面都可以抽象为一个组件树:
那么什么是组件呢?
组件可以扩展HTML元素,封装可重用的HTML代码,我们可以将组件看作自定义的HTML元素。
组件的创建和注册
Vue.js的组件的使用有3个步骤:创建组件构造器、注册组件和使用组件。
一个小小的demo来说明一下,这个就是官方的例子:
<div id="example">
<my-component></my-component>
</div>
// 定义
var MyComponent = Vue.extend({
template: '<div>A custom component!</div>'
})
// 注册
Vue.component('my-component', MyComponent)
// 创建根实例
new Vue({
el: '#example'
})
<div id="example">
<div>A custom component!</div>
</div>
下面的代码演示了这3个步骤:
<!DOCTYPE html>
<html>
<body>
<div id="app">
<!-- 3. #app是Vue实例挂载的元素,应该在挂载元素范围内使用组件-->
<my-component></my-component>
</div>
</body>
<script src="js/vue.js"></script>
<script>
// 1.创建一个组件构造器
var myComponent = Vue.extend({
template: '<div>This is my first component!</div>'
})
// 2.注册组件,并指定组件的标签,组件的HTML标签为<my-component>
Vue.component('my-component', myComponent)
new Vue({
el: '#app'
});
</script>
</html>
运行结果如下:
可以看到,使用组件和使用普通的HTML元素没什么区别。
理解组件的创建和注册
- Vue.extend()是Vue构造器的扩展,调用Vue.extend()创建的是一个组件构造器。
- Vue.extend()构造器有一个选项对象,选项对象的template属性用于定义组件要渲染的HTML。
- 使用Vue.component()注册组件时,需要提供2个参数,第1个参数时组件的标签,第2个参数是组件构造器。
- 组件应该挂载到某个Vue实例下,否则它不会生效。
请注意第4点,以下代码在3个地方使用了标签,但只有#app1和#app2下的标签才起到作用。
<!DOCTYPE html>
<html>
<body>
<div id="app1">
<my-component></my-component>
</div>
<div id="app2">
<my-component></my-component>
</div>
<!--该组件不会被渲染-->
<my-component></my-component>
</body>
<script src="js/vue.js"></script>
<script>
var myComponent = Vue.extend({
template: '<div>This is a component!</div>'
})
Vue.component('my-component', myComponent)
var app1 = new Vue({
el: '#app1'
});
var app2 = new Vue({
el: '#app2'
})
</script>
</html>