Vue.js——60分钟组件快速入门(上篇)

组件简介

组件系统是 Vue.js 其中一个重要的概念,它提供了一种抽象,让我们可以使用独立可复用的小组件来构建大型应用,任意类型的应用界面都可以抽象为一个组件树:

Component Tree

那么什么是组件呢?
组件可以扩展 HTML 元素,封装可重用的 HTML 代码,我们可以将组件看作自定义的 HTML 元素。

本文的 Demo 和源代码已放到 GitHub,如果您觉得本篇内容不错,请点个赞,或在 GitHub 上加个星星!
(所有示例都放在 GitHub Pages 上了,请访问https://github.com/keepfool/vue-tutorials查看示例汇总)

由于组件的篇幅较大,我将会把组件的入门知识分为两篇来讲解,这样也便于各位看官们快速消化。

组件的创建和注册

基本步骤

Vue.js 的组件的使用有 3 个步骤:创建组件构造器、注册组件和使用组件。

image

下面的代码演示了这 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: '&lt;div&gt;This is my first component!&lt;/div&gt;'
	})
	
	// 2.注册组件,并指定组件的标签,组件的HTML标签为&lt;my-component&gt;
	Vue.component('my-component', myComponent)
	
	new Vue({
		el: '#app'
	});
	
&lt;/script&gt;

</html>

运行结果如下:

image

可以看到,使用组件和使用普通的 HTML 元素没什么区别。

理解组件的创建和注册

我们用以下几个步骤来理解组件的创建和注册:

1. Vue.extend()是 Vue 构造器的扩展,调用Vue.extend()创建的是一个组件构造器。
2. Vue.extend()构造器有一个选项对象,选项对象的template属性用于定义组件要渲染的 HTML。
3. 使用Vue.component()注册组件时,需要提供 2 个参数,第 1 个参数时组件的标签,第 2 个参数是组件构造器。
4. 组件应该挂载到某个 Vue 实例下,否则它不会生效。

请注意第 4 点,以下代码在 3 个地方使用了 <my-component> 标签,但只有 #app1 和#app2 下的 <my-component> 标签才起到作用。

<!DOCTYPE html>
<html>
	<body>
		<div id="app1">
			<my-component></my-component>
		</div>
	&lt;div id="app2"&gt;
		&lt;my-component&gt;&lt;/my-component&gt;
	&lt;/div&gt;
	
	&lt;!--该组件不会被渲染--&gt;
	&lt;my-component&gt;&lt;/my-component&gt;
&lt;/body&gt;
&lt;script src="js/vue.js"&gt;&lt;/script&gt;
&lt;script&gt;
	var myComponent = Vue.extend({
		template: '&lt;div&gt;This is a component!&lt;/div&gt;'
	})
	
	Vue.component('my-component', myComponent)
	
	var app1 = new Vue({
		el: '#app1'
	});
	
	var app2 = new Vue({
		el: '#app2'
	})
&lt;/script&gt;

</html>

image

View Demo

全局注册和局部注册

调用Vue.component()注册组件时,组件的注册是全局的,这意味着该组件可以在任意 Vue 示例下使用。
如果不需要全局注册,或者是让组件使用在其它组件内,可以用选项对象的 components 属性实现局部注册

上面的示例可以改为局部注册的方式:

<!DOCTYPE html>
<html>
	<body>
		<div id="app">
			<!-- 3. my-component 只能在 #app 下使用 -->
			<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>'})
	new Vue({
		el: '#app',
		components: {
			// 2. 将myComponent组件注册到Vue实例下
			'my-component' : myComponent
		}
	});
&lt;/script&gt;

</html>

由于 my-component 组件是注册在 #app 元素对应的 Vue 实例下的,所以它不能在其它 Vue 实例下使用。

<div id="app2">
	<!-- 不能使用 my-component 组件,因为 my-component 是一个局部组件,它属于 #app-->
	<my-component></my-component>
</div>

<script>
new Vue({
el: '#app2'
});
</script>

如果你这样做了,浏览器会提示一个错误:

image

View Demo

父组件和子组件

我们可以在组件中定义并使用其他组件,这就构成了父子组件的关系。

<!DOCTYPE html>
<html>
	<body>
		<div id="app">
			<parent-component>
			</parent-component>
		</div>
	</body>
	<script src="js/vue.js"></script>
	<script>
	var Child = Vue.extend({
		template: '&lt;p&gt;This is a child component!&lt;/p&gt;'
	})
	
	var Parent = Vue.extend({
		// 在Parent组件内使用&lt;child-component&gt;标签
		template :'&lt;p&gt;This is a Parent component&lt;/p&gt;&lt;child-component&gt;&lt;/child-component&gt;',
		components: {
			// 局部注册Child组件,该组件只能在Parent组件内使用
			'child-component': Child
		}
	})
	
	// 全局注册Parent组件
	Vue.component('parent-component', Parent)
	
	new Vue({
		el: '#app'
	})
	
&lt;/script&gt;

</html>

这段代码的运行结果如下:

image

我们分几个步骤来理解这段代码:

  1. var Child = Vue.extend(...)定义一了个 Child 组件构造器
  2. var Parent = Vue.extend(...)定义一个 Parent 组件构造器
  3. components: { 'child-component': Child },将 Child 组件注册到 Parent 组件,并将 Child 组件的标签设置为child-component
  4. template :'<p>This is a Parent component</p><child-component></child-component>',在 Parent 组件内以标签的形式使用 Child 组件。
  5. Vue.component('parent-component', Parent) 全局注册 Parent 组件
  6. 在页面中使用 <parent-component> 标签渲染 Parent 组件的内容,同时 Child 组件的内容也被渲染出来

image

Child 组件是在 Parent 组件中注册的,它只能在 Parent 组件中使用,确切地说:子组件只能在父组件的 template 中使用。

请注意下面两种子组件的使用方式是错误的:

1. 以子标签的形式在父组件中使用

<div id="app">
	<parent-component>
		<child-component></child-component>
	</parent-component>
</div>

为什么这种方式无效呢?因为当子组件注册到父组件时,Vue.js 会编译好父组件的模板,模板的内容已经决定了父组件将要渲染的 HTML。
<parent-component>…</parent-component>相当于运行时,它的一些子标签只会被当作普通的 HTML 来执行,<child-component></child-component> 不是标准的 HTML 标签,会被浏览器直接忽视掉。

2. 在父组件标签外使用子组件

<div id="app">
	<parent-component>
	</parent-component>
	<child-component>
	</child-component>
</div>

运行这段代码,浏览器会提示以下错误

image

View Demo

组件注册语法糖

以上组件注册的方式有些繁琐,Vue.js 为了简化这个过程,提供了注册语法糖。

使用 Vue.component() 直接创建和注册组件:

// 全局注册,my-component1 是标签名称
Vue.component('my-component1',{template: '<div>This is the first component!</div>'})

var vm1 = new Vue({
el: '#app1'
})

Vue.component()的第 1 个参数是标签名称,第 2 个参数是一个选项对象,使用选项对象的 template 属性定义组件模板。
使用这种方式,Vue 在背后会自动地调用Vue.extend()

在选项对象的 components 属性中实现局部注册:

var vm2 = new Vue({
	el: '#app2',
	components: {
		// 局部注册,my-component2 是标签名称
		'my-component2': {template: '<div>This is the second component!</div>'},
		// 局部注册,my-component3 是标签名称
		'my-component3': {template: '<div>This is the third component!</div>'}
	}
})

View Demo

使用 script 或 template 标签

尽管语法糖简化了组件注册,但在 template 选项中拼接 HTML 元素比较麻烦,这也导致了 HTML 和 JavaScript 的高耦合性。
庆幸的是,Vue.js 提供了两种方式将定义在 JavaScript 中的 HTML 模板分离出来。

使用 <script> 标签

<!DOCTYPE html>
<html>
	<body>
		<div id="app">
			<my-component></my-component>
		</div>
	&lt;script type="text/x-template" id="myComponent"&gt;
		&lt;div&gt;This is a component!&lt;/div&gt;
	&lt;/script&gt;
&lt;/body&gt;
&lt;script src="js/vue.js"&gt;&lt;/script&gt;
&lt;script&gt;
	
	Vue.component('my-component',{
		template: '#myComponent'
	})
	
	new Vue({
		el: '#app'
	})
	
&lt;/script&gt;

</html>

template 选项现在不再是 HTML 元素,而是一个 id,Vue.js 根据这个 id 查找对应的元素,然后将这个元素内的 HTML 作为模板进行编译。

image

注意:使用 <script> 标签时,type 指定为 text/x-template,意在告诉浏览器这不是一段 js 脚本,浏览器在解析 HTML 文档时会忽略 <script> 标签内定义的内容。

image

使用 <template> 标签

如果使用<template>标签,则不需要指定 type 属性。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<div id="app">
			<my-component></my-component>
		</div>
	&lt;template id="myComponent"&gt;
		&lt;div&gt;This is a component!&lt;/div&gt;
	&lt;/template&gt;
&lt;/body&gt;
&lt;script src="js/vue.js"&gt;&lt;/script&gt;
&lt;script&gt;
	
	Vue.component('my-component',{
		template: '#myComponent'
	})
	
	new Vue({
		el: '#app'
	})
	
&lt;/script&gt;

</html>

在理解了组件的创建和注册过程后,我建议使用 <script> 或 <template> 标签来定义组件的 HTML 模板。
这使得 HTML 代码和 JavaScript 代码是分离的,便于阅读和维护。
另外,在 Vue.js 中,可创建.vue 后缀的文件,在.vue 文件中定义组件,这个内容我会在后面的文章介绍。

组件的 el 和 data 选项

传入 Vue 构造器的多数选项也可以用在 Vue.extend()Vue.component()中,不过有两个特例: datael
Vue.js 规定:在定义组件的选项时,data 和 el 选项必须使用函数。

下面的代码在执行时,浏览器会提出一个错误

Vue.component('my-component', {
	data: {a: 1}
})

image

另外,如果 data 选项指向某个对象,这意味着所有的组件实例共用一个 data。
我们应当使用一个函数作为 data 选项,让这个函数返回一个新对象:

Vue.component('my-component', {data: function(){return {a : 1}
	}
})

使用 props

组件实例的作用域是孤立的。这意味着不能并且不应该在子组件的模板内直接引用父组件的数据。可以使用 props 把数据传给子组件。

props 基础示例

下面的代码定义了一个子组件 my-component,在 Vue 实例中定义了 data 选项。

var vm = new Vue({
	el: '#app',
	data: {
		name: 'keepfool',
		age: 28
	},
	components: {
		'my-component': {
			template: '#myComponent',
			props: ['myName', 'myAge']
		}
	}
})

为了便于理解,你可以将这个 Vue 实例看作 my-component 的父组件。
如果我们想使父组件的数据,则必须先在子组件中定义 props 属性,也就是props: ['myName', 'myAge']这行代码。

定义子组件的 HTML 模板:

<template id="myComponent">
	<table>
		<tr>
			<th colspan="2">
				子组件数据
			</th>
		</tr>
		<tr>
			<td>my name</td>
			<td>{{myName}}</td>
		</tr>
		<tr>
			<td>my age</td>
			<td>{{myAge}}</td>
		</tr>
	</table>
</template>

将父组件数据通过已定义好的 props 属性传递给子组件:

<div id="app">
	<my-component v-bind:my-name="name" v-bind:my-age="age"></my-component>
</div>

注意:在子组件中定义 prop 时,使用了 camelCase 命名法。由于 HTML 特性不区分大小写,camelCase 的 prop 用于特性时,需要转为 kebab-case(短横线隔开)。例如,在 prop 中定义的 myName,在用作特性时需要转换为 my-name。

View Demo

这段程序的运行结果如下:

image

父组件是如何将数据传给子组件的呢?相信看了下面这图,也许你就能很好地理解了。

image

在父组件中使用子组件时,通过以下语法将数据传递给子组件:

<child-component v-bind: 子组件 prop="父组件数据属性"></child-component>

prop 的绑定类型

单向绑定

既然父组件将数据传递给了子组件,那么如果子组件修改了数据,对父组件是否会有所影响呢?
我们将子组件模板和页面 HTML 稍作更改:

<div id="app">
&lt;table&gt;
	&lt;tr&gt;
		&lt;th colspan="3"&gt;父组件数据&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td&gt;name&lt;/td&gt;
		&lt;td&gt;{{ name }}&lt;/td&gt;
		&lt;td&gt;&lt;input type="text" v-model="name" /&gt;&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td&gt;age&lt;/td&gt;
		&lt;td&gt;{{ age }}&lt;/td&gt;
		&lt;td&gt;&lt;input type="text" v-model="age" /&gt;&lt;/td&gt;
	&lt;/tr&gt;
&lt;/table&gt;

&lt;my-component v-bind:my-name="name" v-bind:my-age="age"&gt;&lt;/my-component&gt;

</div>

<template id="myComponent">
<table>
<tr>
<th colspan="3"> 子组件数据 </td>
</tr>
<tr>
<td>my name</td>
<td>{{myName}}</td>
<td><input type="text" v-model="myName" /></td>
</tr>
<tr>
<td>my age</td>
<td>{{myAge}}</td>
<td><input type="text" v-model="myAge" /></td>
</tr>
</table>
</template>

View Demo

运行这个页面,我们做两个小试验:

1. 在页面上修改子组件的数据

7

修改了子组件的数据,没有影响父组件的数据。

2. 在页面上修改父组件的数据

8

修改了父组件的数据,同时影响了子组件。

prop 默认是单向绑定:当父组件的属性变化时,将传导给子组件,但是反过来不会。这是为了防止子组件无意修改了父组件的状态

双向绑定

可以使用.sync显式地指定双向绑定,这使得子组件的数据修改会回传给父组件。

<my-component v-bind:my-name.sync="name" v-bind:my-age.sync="age"></my-component>

9

View Deom

单次绑定

可以使用.once显式地指定单次绑定,单次绑定在建立之后不会同步之后的变化,这意味着即使父组件修改了数据,也不会传导给子组件。

<my-component v-bind:my-name.once="name" v-bind:my-age.once="age"></my-component>

10

View Deom

示例

为了尽快消化这些知识,我们来做一个小示例吧。

<!DOCTYPE html>
<html>
&lt;head&gt;
	&lt;meta charset="UTF-8"&gt;
	&lt;title&gt;&lt;/title&gt;
	&lt;link rel="stylesheet" href="styles/demo.css" /&gt;
&lt;/head&gt;

&lt;body&gt;
	&lt;div id="app"&gt;
		&lt;div id="searchBar"&gt;
			Search &lt;input type="text" v-model="searchQuery" /&gt;
		&lt;/div&gt;
		&lt;simple-grid :data="gridData" :columns="gridColumns" :filter-key="searchQuery"&gt;
		&lt;/simple-grid&gt;
	&lt;/div&gt;

	&lt;template id="grid-template"&gt;
		&lt;table&gt;
			&lt;thead&gt;
				&lt;tr&gt;
					&lt;th v-for="col in columns"&gt;
						{{ col | capitalize}}
					&lt;/th&gt;
				&lt;/tr&gt;
			&lt;/thead&gt;
			&lt;tbody&gt;
				&lt;tr v-for="entry in data | filterBy filterKey"&gt;
					&lt;td v-for="col in columns"&gt;
						{{entry[col]}}
					&lt;/td&gt;
				&lt;/tr&gt;
			&lt;/tbody&gt;
		&lt;/table&gt;
	&lt;/template&gt;

&lt;/body&gt;
&lt;script src="js/vue.js"&gt;&lt;/script&gt;
&lt;script&gt;
	Vue.component('simple-grid', {
		template: '#grid-template',
		props: {
			data: Array,
			columns: Array,
			filterKey: String
		}
	})

	var demo = new Vue({
		el: '#app',
		data: {
			searchQuery: '',
			gridColumns: ['name', 'age', 'sex'],
			gridData: [{
				name: 'Jack',
				age: 30,
				sex: 'Male'
			}, {
				name: 'Bill',
				age: 26,
				sex: 'Male'
			}, {
				name: 'Tracy',
				age: 22,
				sex: 'Female'
			}, {
				name: 'Chris',
				age: 36,
				sex: 'Male'
			}]
		}
	})
&lt;/script&gt;

</html>

View Demo

除了以上介绍的知识点,这个示例还用到了两个知识点:

1. prop 验证

props: {
	data: Array,
	columns: Array,
	filterKey: String
}

这段代码表示:父组件传递过来的 data 和 columns 必须是 Array 类型,filterKey 必须是字符串类型。
更多 prop 验证的介绍,请参考:官方文档 prop 验证

2. filterBy 过滤器

可以根据指定的字符串过滤数据。

11

总结

使用组件的前提是创建并注册组件,本篇文章详细介绍了组件从创建到使用的步骤,并介绍了几种不同的方式去创建和注册组件;然后介绍了组件的 props 选项,它用于将父组件的数据传递给子组件,最后我们用一个小的示例演示了这些知识点。