1. 程式人生 > >Vue 組件&組件之間的通信 之組件的介紹

Vue 組件&組件之間的通信 之組件的介紹

大小 charset cli lan 分享 load 擴展 closed htm

什麽是組件?

技術分享圖片

組件Component,可擴展HTML元素,封裝可重用的代碼。通俗的來說,組件將可重用的HTML元素封裝成為標簽方便復用;

組件的使用:

1、使用全局的方法Vue.extend創建構造器;

2、再使用全局的方法Vue.component註冊組件;

註意:在Vue.component裏需要指明組件的名稱,組件名稱不能使用內置標簽名稱,如body.推薦使用短橫線命名規則。

如:

my-component 正確 (推薦使用)

my-Component 錯誤

mycomponent 正確

Mycomponent 正確

myComponent 錯誤

MyComponent 錯誤

示例:

技術分享圖片

vue 代碼:

<script>
            window.onload= () =>{
                
                
                
                //創建構造器
                let myComponent=Vue.extend({
                    
                    template:"<h1>歡迎來到perfect*的博客園</h1>
" }); //註冊組件 Vue.component(my-component,myComponent); new Vue({ el:div, data:{ } })}
</script>

html:

<div>
            <my-component></my-component>
           
            
            
        </div>

使用註冊組件簡寫的方式:

出現的問題:

技術分享圖片

技術分享圖片

修改後的效果:

技術分享圖片

vue代碼:

//註冊組件的簡寫方式
                
                Vue.component(my-componenta,{
                    
                    template:<h2>hello vue</h2>
                });
                

html:

<my-componentA></my-componentA>

html標簽是大小寫不分的

組件的命名不支持駝峰命名方式

最終所有代碼:

技術分享圖片
 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title>component</title>
 6         <script type="text/javascript" src="../js/vue.js" ></script>
 7         
 8         <script>
 9             window.onload= () =>{
10                 
11                 
12                 
13                 //創建構造器
14                 let myComponent=Vue.extend({
15                     
16                     template:"<h1>歡迎來到perfect*的博客園</h1>"
17                 });
18                 
19                 //註冊組件
20                 Vue.component(my-component,myComponent);
21                 
22                 
23                 
24                 
25                 //註冊組件的簡寫方式
26                 
27                 Vue.component(my-componenta,{
28                     
29                     
30                     template:<h2>hello vue</h2>
31                 });
32                 
33                 
34                 
35                 new Vue({
36                 el:div,
37                 data:{
38                     
39                     
40                 }
41                 
42                 
43                 
44                 
45                 
46             })}
47         </script>
48     </head>
49     <body>
50         <div>
51             <my-component></my-component>
52             <my-componentA></my-componentA>
53            
54             
55             
56         </div>
57     </body>
58 </html>
組件的介紹

詳細介紹見官網:https://cn.vuejs.org/v2/api/#%E5%85%A8%E5%B1%80-API

Vue 組件&組件之間的通信 之組件的介紹