一、組件命名的方式
①kebab-case,單詞之間採用 - (短橫線)連接,例如:my-component ,在DOM中使用時,<my-component ></my-component >
②PascalCase,駝峯式名稱,單詞之間,首字母大寫,例如:MyComponent,但是在DOM中使用時,必須更改爲,<my-component ></my-component >,<MyComponent></MyComponent>是識別不了的。
二、全局註冊
①通過Vue.extend()和Vue.component()註冊
// 方式1
var tmp1 = Vue.extend({
template: "<p>通過 Vue.extend 創建的 tmp1 組件</p>"
});
Vue.component("tmp1", tmp1);
// 方式2
Vue.component("tmp2", Vue.extend({
template: "<p>通過 Vue.extend 創建的 tmp2 組件</p>"
}));
②通過Vue.component()字面量註冊
Vue.component("tmp3", {
template: "<h3>通過字面量方式創建的tmp3組件</h3>"
});
③通過<template id="tmp1"> 方式註冊
js部分:
Vue.component("tmp4", {
template: "#template1"
});
HTML部分:
<template id="template1">
<h4>這是通過 app 外部 template 標籤自定義的 tmp4 組件</h4>
</template>
三、定義局部組件
局部組件定義在vue實例內部,該組件只能在vue實例控制範圍內才能使用
JS部分:
var app2 = new Vue({
el: "#app2",
components: {
"temp5": {
template: "<h1>app2 的局部組件 h1 </h1>"
},
"temp6":{
template:"<h2>app2 的局部組件 h2 </h2>"
}
}
});
HTML部分:
<div id="app">
<!-- 在這裏使用app2註冊的局部組件會報錯 -->
<!-- <temp5></temp5> -->
</div>
<div id="app2">
<temp5></temp5>
</div>
在app中使用了temp5組件會報以下警告:
[Vue warn]: Unknown custom element: <temp5> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
錯誤原因:
HTML 中的標籤名是大小寫不敏感的,所以瀏覽器會把所有大寫字符解釋爲小寫字符。這意味着當你使用 DOM 中的模板時,使用駝峯命名法 的 prop 名需要使用其等價的短橫線分隔命名方法或者全部使用小寫。否者就會報上述錯誤。