組件名大小寫
定義組件名的方式有兩種:
使用 kebab-case
Vue.component('my-component-name', { /* ... */ })
當(dāng)使用 kebab-case (短橫線分隔命名) 定義一個組件時,你也必須在引用這個自定義元素時使用 kebab-case,例如 <my-component-name>蹬昌。
使用 PascalCase
Vue.component('MyComponentName', { /* ... */ })
當(dāng)使用 PascalCase (首字母大寫命名) 定義一個組件時襟铭,你在引用這個自定義元素時兩種命名法都可以使用盏求。也就是說 <my-component-name> 和 <MyComponentName> 都是可接受的噪漾。注意充活,盡管如此蜂莉,直接在 DOM (即非字符串的模板) 中使用時只有 kebab-case 是有效的。
全局注冊
全局組件[要注冊一個全局組件混卵,可以使用 Vue.component(tagName, options)]【注意點:組件在注冊之后映穗,便可以作為【自定義元素】在一個實例的模板中使用,確保在初始化根實例之前注冊組件幕随∫献蹋】
Vue.component('my-component-name', {
// ... 選項 ...
})
局部注冊
局部組件[注意點:注冊僅在其作用域中可用的組件]
在這些情況下,你可以通過一個普通的 JavaScript 對象來定義組件:
var ComponentA = { /* ... */ }
var ComponentB = { /* ... */ }
var ComponentC = { /* ... */ }
然后在 components 選項中定義你想要使用的組件:
new Vue({
el: '#app',
components: {
'component-a': ComponentA,
'component-b': ComponentB
}
})
對于 components 對象中的每個屬性來說赘淮,其屬性名就是自定義元素的名字辕录,其屬性值就是這個組件的選項對象。
注意局部注冊的組件在其子組件中不可用梢卸。例如走诞,如果你希望 ComponentA 在 ComponentB 中可用,則你需要這樣寫:
var ComponentA = { /* ... */ }
var ComponentB = {
components: {
'component-a': ComponentA
},
// ...
}
或者如果你通過 Babel 和 webpack 使用 ES2015 模塊蛤高,那么代碼看起來更像:
import ComponentA from './ComponentA.vue'
export default {
components: {
ComponentA
},
// ...
}
關(guān)于全局組件和局部組件的具體實例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app1">
<h4>全局組件</h4>
<my-global></my-global>
</div>
<p></p>
<hr>
<p></p>
<div id="app2">
<h4>局部組件</h4>
<local-global></local-global>
</div>
<script src="js/vue.js"></script>
<script>
// 先注冊全局組件
Vue.component('my-global',{
template: '<div>{{msg}}</div>',
data () {
return {
msg: 'A global component'
}
}
});
// 再初始化
var app1 = new Vue({
el: '#app1'
});
var child = {
template: '<div>a local component</div>'
};
var app2 = new Vue({
el: '#app2',
data: {
},
components: {
// 局部組件
'local-global': child
}
});
</script>
</body>
</html>
在模塊系統(tǒng)中局部注冊
創(chuàng)建一個 components 目錄蚣旱,并將每個組件放置在其各自的文件中。然后你需要在局部注冊之前導(dǎo)入每個你想使用的組件戴陡。例如塞绿,在一個假設(shè)的 ComponentB.js 或 ComponentB.vue 文件中,現(xiàn)在 ComponentA 和 ComponentC 都可以在 ComponentB 的模板中使用了恤批。
import ComponentA from './ComponentA'
import ComponentC from './ComponentC'
export default {
components: {
ComponentA,
ComponentC
},
// ...
}