vue 組件-組件定義的4種方式


一、組件命名的方式

  ①kebab-case,單詞之間采用  - (短橫線)連接,例如:my-component ,在DOM中使用時,<my-component ></my-component >

  ②PascalCase,駝峰式名稱,單詞之間,首字母大寫,例如:MyComponent,但是在DOM中使用時,必須更改為,<my-component ></my-component >,<MyComponent></MyComponent>是識別不了的。

 

二、全局注冊

①通過Vue.extend()和Vue.component()注冊

 1     // 方式1
 2     var tmp1 = Vue.extend({
 3         template: "<p>通過 Vue.extend 創建的 tmp1 組件</p>"
 4     });
 5     Vue.component("tmp1", tmp1);
 6 
 7 
 8     // 方式2
 9     Vue.component("tmp2", Vue.extend({
10         template: "<p>通過 Vue.extend 創建的 tmp2 組件</p>"
11     }));

 

②通過Vue.component()字面量注冊

1     Vue.component("tmp3", {
2         template: "<h3>通過字面量方式創建的tmp3組件</h3>"
3     });

 

③通過<template id="tmp1"> 方式注冊

js部分:

1     Vue.component("tmp4", {
2         template: "#template1"
3     });

HTML部分:

1 <template id="template1">
2     <h4>這是通過 app 外部 template 標簽自定義的 tmp4 組件</h4>
3 </template>

 

三、定義局部組件

局部組件定義在vue實例內部,該組件只能在vue實例控制范圍內才能使用

JS部分:

 1     var app2 = new Vue({
 2         el: "#app2",
 3         components: {
 4             "temp5": {
 5                 template: "<h1>app2 的局部組件 h1 </h1>"
 6             },
 7             "temp6":{
 8                 template:"<h2>app2 的局部組件 h2 </h2>"
 9             }
10         }
11     });

HTML部分:

1     <div id="app">
2         <!-- 在這里使用app2注冊的局部組件會報錯 -->
3         <!-- <temp5></temp5> -->
4     </div>
5 
6     <div id="app2">
7         <temp5></temp5>
8     </div>

如果在app中使用了temp5組件會報以下警告:

1 [Vue warn]: Unknown custom element: <temp5> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM