一、组件命名的方式
①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 名需要使用其等价的短横线分隔命名方法或者全部使用小写。否者就会报上述错误。