Vue組件入門

組件簡介#

組件系統:組件系統是Vue.js其中一個重要的概念,它提供了一種抽象,讓我們可以使用獨立可復用的小組件來構建大型應用,任意類型的應用界面都可以抽象為一個組件樹:

抽象成組件樹

組件:組件可以擴展HTML元素,封裝可重用的HTML代碼,我們可以將組件看作自定義的HTML元素。

組件的創建和注冊#

使用Vue.js組件的三個步驟:創建組件構造器、注冊組件和使用組件

三個步驟

例子如下:

<!DOCTYPE html>
<html>
    <body>
        <div id="app">
            <!-- 3. #app是Vue實例掛載的元素,應該在掛載元素范圍內使用組件-->
            <my-component></my-component>
        </div>
    </body>
    <script src="js/vue.js"></script>
    <script>
    
        // 1.創建一個組件構造器
        var myComponent = Vue.extend({
            template: '<div>This is my first component!</div>'
        })
        
        // 2.注冊組件,并指定組件的標簽,組件的HTML標簽為<my-component>
        Vue.component('my-component', myComponent)
        
        new Vue({
            el: '#app'
        });
        
    </script>
</html>

理解##

  • Vue.extend()是Vue構造器的擴展,調用Vue.extend()創建的是一個組建的構造器
  • Vue.extend()構造器有一個選項對象,選項對象的template屬性用于定義組件要渲染的HTML
  • 使用Vue.component()注冊組件的時候,需要提供兩個參數,第一個是參數時組件的標簽,第二個參數是組件的構造器
  • 組件應該掛載到Vue實例下,否則它不會生效

全局注冊和局部注冊##

調用Vue.component()注冊組件時,組件的注冊是全局的,這意味著該組件可以在任意Vue示例下使用。
如果不需要全局注冊,或者是讓組件使用在其它組件內,可以用選項對象的components屬性實現局部注冊。
上面的示例可以改為局部注冊的方式:

<!DOCTYPE html>
<html>
    <body>
        <div id="app">
            <!-- 3. my-component只能在#app下使用-->
            <my-component></my-component>
        </div>
    </body>
    <script src="js/vue.js"></script>
    <script>
        // 1.創建一個組件構造器
        var myComponent = Vue.extend({
            template: '<div>This is my first component!</div>'
        })
        
        new Vue({
            el: '#app',
            components: {
                // 2. 將myComponent組件注冊到Vue實例下
                'my-component' : myComponent
            }
        });
    </script>
</html>

由于my-component組件是注冊在#app元素對應的Vue實例下的,所以它不能在其它Vue實例下使用。

<div id="app2">
    <!-- 不能使用my-component組件,因為my-component是一個局部組件,它屬于#app-->
    <my-component></my-component>
</div>

<script>
    new Vue({
        el: '#app2'
    });
</script>
錯誤

父組件和子組件##

我們可以在組件中定義并使用其他組件,這就構成了父子組件的關系。

<!DOCTYPE html>
<html>
    <body>
        <div id="app">
            <parent-component>
            </parent-component>
        </div>
    </body>
    <script src="js/vue.js"></script>
    <script>
        
        var Child = Vue.extend({
            template: '<p>This is a child component!</p>'
        })
        
        var Parent = Vue.extend({
            // 在Parent組件內使用<child-component>標簽
            template :'<p>This is a Parent component</p><child-component></child-component>',
            components: {
                // 局部注冊Child組件,該組件只能在Parent組件內使用
                'child-component': Child
            }
        })
        
        // 全局注冊Parent組件
        Vue.component('parent-component', Parent)
        
        new Vue({
            el: '#app'
        })
    </script>
</html>
  • var Child = Vue.extend(...)定義一了個Child組件構造器
  • var Parent = Vue.extend(...)定義一個Parent組件構造器
  • components: { 'child-component': Child },將Child組件注冊到Parent組件,并將Child組件的標簽設置為child-component。
    -template :'<p>This is a Parent component</p><child-component></child-component>',在Parent組件內以標簽的形式使用Child組件。
  • Vue.component('parent-component', Parent)全局注冊Parent組件
  • 在頁面中使用<parent-component>標簽渲染Parent組件的內容,同時Child組件的內容也被渲染出來
過程

Child組件是在Parent組件中注冊的,它只能在Parent組件中使用,確切地說:子組件只能在父組件的template中使用。

請注意下面兩種子組件的使用方式是錯誤的:

  1. 以子標簽的形式在父組件中使用
<div id="app">
    <parent-component>
        <child-component></child-component>
    </parent-component>
</div>

為什么這種方式無效呢?因為當子組件注冊到父組件時,Vue.js會編譯好父組件的模板,模板的內容已經決定了父組件將要渲染的HTML。
<parent-component>…</parent-component>相當于運行時,它的一些子標簽只會被當作普通的HTML來執行,<child-component></child-component>不是標準的HTML標簽,會被瀏覽器直接忽視掉。

  1. 在父組件標簽外使用子組件
<div id="app">
    <parent-component>
    </parent-component>
    <child-component>
    </child-component>
</div>

運行這段代碼,瀏覽器會提示以下錯誤

組件注冊語法糖##

以上組件注冊的方式有些繁瑣,Vue.js為了簡化這個過程,提供了注冊語法糖。
使用Vue.component()直接創建和注冊組件:

// 全局注冊,my-component1是標簽名稱
Vue.component('my-component1',{
    template: '<div>This is the first component!</div>'
})

var vm1 = new Vue({
    el: '#app1'
})

Vue.component()的第1個參數是標簽名稱,第2個參數是一個選項對象,使用選項對象的template屬性定義組件模板。
使用這種方式,Vue在背后會自動地調用Vue.extend()。
在選項對象的components屬性中實現局部注冊:

var vm2 = new Vue({
    el: '#app2',
    components: {
        // 局部注冊,my-component2是標簽名稱
        'my-component2': {
            template: '<div>This is the second component!</div>'
        },
        // 局部注冊,my-component3是標簽名稱
        'my-component3': {
            template: '<div>This is the third component!</div>'
        }
    }
})

使用script或template標簽##

盡管語法糖簡化了組件注冊,但在template選項中拼接HTML元素比較麻煩,這也導致了HTML和JavaScript的高耦合性。
慶幸的是,Vue.js提供了兩種方式將定義在JavaScript中的HTML模板分離出來。

使用<script>標簽

<!DOCTYPE html>
<html>
    <body>
        <div id="app">
            <my-component></my-component>
        </div>
        
        <script type="text/x-template" id="myComponent">
            <div>This is a component!</div>
        </script>
    </body>
    <script src="js/vue.js"></script>
    <script>
        
        Vue.component('my-component',{
            template: '#myComponent'
        })
        
        new Vue({
            el: '#app'
        })
        
    </script>
</html>

template選項現在不再是HTML元素,而是一個id,Vue.js根據這個id查找對應的元素,然后將這個元素內的HTML作為模板進行編譯。


注意:使用<script>標簽時,type指定為text/x-template,意在告訴瀏覽器這不是一段js腳本,瀏覽器在解析HTML文檔時會忽略<script>標簽內定義的內容。

使用<template>標簽

如果使用<template>標簽,則不需要指定type屬性。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
            <my-component></my-component>
        </div>
        
        <template id="myComponent">
            <div>This is a component!</div>
        </template>
    </body>
    <script src="js/vue.js"></script>
    <script>
        
        Vue.component('my-component',{
            template: '#myComponent'
        })
        
        new Vue({
            el: '#app'
        })
        
    </script>
</html>

在理解了組件的創建和注冊過程后,我建議使用<script>或<template>標簽來定義組件的HTML模板。
這使得HTML代碼和JavaScript代碼是分離的,便于閱讀和維護。
另外,在Vue.js中,可創建.vue后綴的文件,在.vue文件中定義組件,這個內容我會在后面的文章介紹。

組件的el和data選項##

傳入Vue構造器的多數選項也可以用在 Vue.extend() 或Vue.component()中,不過有兩個特例: data 和el。
Vue.js規定:在定義組件的選項時,data和el選項必須使用函數。

下面的代碼在執行時,瀏覽器會提出一個錯誤

Vue.component('my-component', {
    data: {
        a: 1
    }
})

另外,如果data選項指向某個對象,這意味著所有的組件實例共用一個data。
我們應當使用一個函數作為 data 選項,讓這個函數返回一個新對象:

Vue.component('my-component', {
  data: function(){
      return {a : 1}
  }
})

原文鏈接:Vue.js——60分鐘組件快速入門(上篇)

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,501評論 6 544
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,673評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,610評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,939評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,668評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,004評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,001評論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,173評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,705評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,426評論 3 359
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,656評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,139評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,833評論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,247評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,580評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,371評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,621評論 2 380

推薦閱讀更多精彩內容