Vue Component Registration

組件名稱

每個組件都會有個名稱,位置放在第一個參數。

1
Vue.component('my-component-name', { /* ... */ })

kebab-case 命名

kebab-case 指的是用 - 分隔命名,使用 kebab-case 命名時,引用的時候也要用 kebab-case <my-component-name>

PascalCase 命名

PascalCase 是首字母大寫命名,用 PascalCase 引用的時候 <my-component-name><MyComponentName> 都是可以的,但要注意在 DOM(非字串模板) 中,只有 kebab-case 才有效。

推薦的作法是使用全小寫並用 - 連接,來避免和 HTML 衝突。

全局註冊

使用 Vue.component 建立的組件是全局的,在註冊之後可以用在任何根實體(root Vue instance(new Vue))內。範例如下:

1
2
3
4
5
6
// 註冊三個組件
Vue.component('component-a', { /* ... */ })
Vue.component('component-b', { /* ... */ })
Vue.component('component-c', { /* ... */ })

new Vue({ el: '#app' })
1
2
3
4
5
6
<!-- 在根實體中使用 -->
<div id="app">
<component-a></component-a>
<component-b></component-b>
<component-c></component-c>
</div>

在各子組件(subcomponents)中也能使用,也就是說這三個組件在各自的內部也可以互相使用。

局部註冊

如果你使用了 webpack,全局註冊會讓你即使沒再用一個組件了,該組件仍會被包到最終的構建結果裡。
若是想避免這個狀況,可以直接用一個物件來定義組件:

1
2
3
var ComponentA = { /* ... */ }
var ComponentB = { /* ... */ }
var ComponentC = { /* ... */ }

然後在 components 中定義你想使用的組件

1
2
3
4
5
6
7
8
new Vue({
el: '#app',
components: {
// 屬性名為組件名
'component-a': ComponentA,
'component-b': ComponentB
}
})

不過局部註冊的組件在子組件中不可以使用,除非用下面的寫法

1
2
3
4
5
6
7
8
var ComponentA = { /* ... */ }

var ComponentB = {
components: {
'component-a': ComponentA
},
// ...
}

如果通過 Babel 和 Webpack 使用 ES6 模組(modules),則寫法如下

1
2
3
4
5
6
7
8
import ComponentA from './ComponentA.vue'

export default {
components: {
ComponentA
},
// ...
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×