Vue_ 元件Component

定義

Vue 應用程式的使用,主要是以 Vue component 元件 所組成,而最上層是以 Root 為主,下面包含 Header, Content 與 side (不同的 component )。而每個 Component 當中的 data 都會是互相獨立的,使用前端框架的好處在於,很多時候同樣重複的事情,你只需要做一次,就能重複使用,並且在後面的維護上更為方便。

  • 首先用Vue.component()方法
  • 第一個參數是component的名字(component 命名用全小寫以 dash 分隔)
  • 第二個參數是一個物件,其中用 templete 的字串定義組件的視覺元素(直接定義html的內容)
  • 重點! component的宣告必須在 vue 實例 new之前!

原寫法(無使用元件)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<body>

<div id="app">
<button @click="count++">You clicked me {{ count }} times.</button>
</div>

</body>


var app = new Vue({
el: '#app',
data: {
count: 0
}
});

元件寫法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

<body>

<div id="app">
<button-counter></button-counter>
<button-counter></button-counter>
</div>

</body>

Vue.component('button-counter', {
data: function () {
return {
count: 0
}
},
template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})

x-template使用時機

若是 template 中的語法太過複雜,會使用 x-template 的方式來改善程式的可讀性。 x-template 的宣告必須在另一個 script元素中,並為其帶上 text/x-template 的類型,然後通過一個 id 將模板引用過去。

1
2
3
4
5
6
7
8
9
10
11
12
<script  type="text/x-template"  id="rowCompTemp">
<tr>
<td>{‌{ person.name }}</td>
<td>{‌{ person.cash }}</td>
<td>{‌{ person.icash }}</td>
</tr>
</script>

Vue.component('row-comp', {
props: ['person'],
template: '#rowCompTemp'
})

元件使用方式(全域、區域註冊)

Global 全域註冊

如果有元件共用的需求,我們會使用Vue.component 語法來註冊一個元件,在註冊全域元件時要給予兩個參數,分別為「組件名稱」及「選項物件」,在下方範例中「組件名稱」為 component-layout ,「選項物件」則為其後的內容。

不過使用全域註冊的缺點是,不管有沒有使用到這個元件,其元件就一定會載入,因此,使用全域註冊會將原本不需要的組件載入進來,整體而言,會拖慢網頁載入的時間。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

<div id=”app”>
<component-layout></component-layout>
</div>

<script>
Vue.component("component-layout", {
template: `<div>{{text}}</div>`,
data(){
return{
text:'我是全域註冊'
}
}
});

let vm = new Vue({
el: "#app"
});
<script>
Local 局部註冊

如同前面所提,考量全域註冊的缺點,某些特定元件就會用區域註冊的方式,註冊在需要使用它的元件之中,同時,它是一個選項物件,可以由 components 這個選項物件屬性載入 Vue 實例 使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

<div id=”app”>
<component-layout></component-layout>
</div>


<script>
let vm = new Vue({
el: "#app",
components:{
'component-layout' :{
template: `<div>{{text}}</div>`,
data(){
return {
text:'我是局部註冊'
}
}
}
}
});
<script>