Vue.js——60分鐘組件快速入門(上篇)

組件簡介

組件系統是Vue.js其中一個重要的概念,它提供了一種抽象,讓咱們可使用獨立可複用的小組件來構建大型應用,任意類型的應用界面均可以抽象爲一個組件樹:javascript

Component Tree

那麼什麼是組件呢?
組件能夠擴展HTML元素,封裝可重用的HTML代碼,咱們能夠將組件看做自定義的HTML元素。css

本文的Demo和源代碼已放到GitHub,若是您以爲本篇內容不錯,請點個贊,或在GitHub上加個星星!
(全部示例都放在GitHub Pages上了,請訪問https://github.com/keepfool/vue-tutorials查看示例彙總)html

因爲組件的篇幅較大,我將會把組件的入門知識分爲兩篇來說解,這樣也便於各位看官們快速消化。vue

組件的建立和註冊

基本步驟

Vue.js的組件的使用有3個步驟:建立組件構造器、註冊組件和使用組件。java

image

下面的代碼演示了這3個步驟:git

<!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>

運行結果以下:github

image

能夠看到,使用組件和使用普通的HTML元素沒什麼區別。api

理解組件的建立和註冊

咱們用如下幾個步驟來理解組件的建立和註冊:瀏覽器

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>標籤才起到做用。app

<!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>

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
			}
		});
	</script>
</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: '<p>This is a child component!</p>'
		})
		
		var Parent = Vue.extend({
			// 在Parent組件內使用<child-component>標籤
			template :'<p>This is a Parent component</p><child-component></child-component>',
			components: {
				// 局部註冊Child組件,該組件只能在Parent組件內使用
				'child-component': Child
			}
		})
		
		// 全局註冊Parent組件
		Vue.component('parent-component', Parent)
		
		new Vue({
			el: '#app'
		})
		
	</script>
</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>
		
		<script type="text/x-template" id="myComponent">
			<div>This is a component!</div>
		</script>
	</body>
	<script src="js/vue.js"></script>
	<script>
		
		Vue.component('my-component',{
			template: '#myComponent'
		})
		
		new Vue({
			el: '#app'
		})
		
	</script>
</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>
		
		<template id="myComponent">
			<div>This is a component!</div>
		</template>
	</body>
	<script src="js/vue.js"></script>
	<script>
		
		Vue.component('my-component',{
			template: '#myComponent'
		})
		
		new Vue({
			el: '#app'
		})
		
	</script>
</html>

在理解了組件的建立和註冊過程後,我建議使用<script>或<template>標籤來定義組件的HTML模板。
這使得HTML代碼和JavaScript代碼是分離的,便於閱讀和維護。
另外,在Vue.js中,可建立.vue後綴的文件,在.vue文件中定義組件,這個內容我會在後面的文章介紹。

組件的el和data選項

傳入Vue構造器的多數選項也能夠用在 Vue.extend() 或Vue.component()中,不過有兩個特例: data 和el
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">

	<table>
		<tr>
			<th colspan="3">父組件數據</td>
		</tr>
		<tr>
			<td>name</td>
			<td>{{ name }}</td>
			<td><input type="text" v-model="name" /></td>
		</tr>
		<tr>
			<td>age</td>
			<td>{{ age }}</td>
			<td><input type="text" v-model="age" /></td>
		</tr>
	</table>

	<my-component v-bind:my-name="name" v-bind:my-age="age"></my-component>
</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>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<link rel="stylesheet" href="styles/demo.css" />
	</head>

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

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

	</body>
	<script src="js/vue.js"></script>
	<script>
		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'
				}]
			}
		})
	</script>

</html>

View Demo

除了以上介紹的知識點,這個示例還用到了兩個知識點:

1. prop驗證

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

這段代碼表示:父組件傳遞過來的data和columns必須是Array類型,filterKey必須是字符串類型。
更多prop驗證的介紹,請參考:官方文檔prop驗證

2. filterBy過濾器

能夠根據指定的字符串過濾數據。

11

總結

使用組件的前提是建立並註冊組件,本篇文章詳細介紹了組件從建立到使用的步驟,並介紹了幾種不一樣的方式去建立和註冊組件;而後介紹了組件的props選項,它用於將父組件的數據傳遞給子組件,最後咱們用一個小的示例演示了這些知識點。

相關文章
相關標籤/搜索