1. 程式人生 > >組件快速入門

組件快速入門

ima git div images 創建模板 text 解析 get lan

前言

最近開始在學vue相關的內容。組件這章的內容比較多。看了http://www.cnblogs.com/keepfool/p/5625583.html這篇博客,博主總結的還比較全面也挺清晰,可是這篇博客的知識點跟實例都是基於vue 1.0版本的,所以參考這篇博客,我將vue2.0版本中的相關知識點做了一個總結。算是自己學習的一個筆記

什麽是組件?

組件 (Component) 是 Vue.js 最強大的功能之一。組件可以擴展 HTML 元素,封裝可重用的代碼。我們可以將組件看成是封裝好的HTML元素。

本文的所有代碼,都放在github上面https://github.com/xuxiaozhi/vue-tutorial,有需要的可以下載查看。

組件的註冊和使用

全局註冊

註冊一個組件

要註冊一個全局組件,你可以使用 Vue.component(tagName, options)來註冊。如下實例:

        //1、註冊一個全局的組件。要確保在初始化實例之前註冊
        Vue.component(‘my-component‘,{
            template:"<div>這是第一個組件</div>"
        })
        
        //創建跟實例
        new Vue({
            el:"#app"
        })

使用組件

組件在註冊之後,便可以在父實例的模塊中以自定義元素 <my-component></my-component>

的形式使用。

註意:要確保組件是在初始化實例之前註冊,要不然使用的時候會報錯

        <div id="app">
            <my-component></my-component>
        </div>

組件使用後在頁面中,將渲染成以下結構

技術分享

局部註冊組件

我們不必全局註冊每一個組件,根據實際情況需要,我們可以采用局部註冊的方式註冊組件。如下實例

        new Vue({
            el:"#app",
            components:{
                
‘my-component‘:{ template:"<div>這個是局部註冊的組件</div>" } } })

?註意

局部註冊的組件僅在當前註冊的實例或者組件內部使用。在其他地方引用將會報錯,如下:

        <div id="app">
            <my-component></my-component>
        </div>
        <div id="app2">
            <my-component></my-component>
        </div>

在上述實例中,我們在”#app“元素所在的實例中,註冊了一個組件,然後在“#app”和“#app2”內引用,查看源代碼發現,只有“#app”內的組件渲染成了html代碼,而在“#app2”內只是一個無意義的標簽,如下圖所示:

技術分享

字符串模板

在組件中,我們一般使用字符串模板,字符串模板,主要有以下三種形式

  • 使用script標簽
  • 使用template標簽
  • 單文件組件

使用<script標簽

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>組件相關</title>
    </head>
    <body>
        <div id="app">
            <my-component></my-component>
        </div>
        <script type="text/x-template" id="myComponent">
            <div>這是script模板</div>
        </script>
    </body>
    <script type="text/javascript" src="../js/vue.js" ></script>
    <script type="text/javascript">
        
        //全局註冊一個組件
        Vue.component(my-component,{
            template:"#myComponent"
        })
        
        new Vue({
            el:"#app"
        })
    </script>
</html>
註意點:
  1. 需要給script設置一個id,使用的時候,直接引用該id即可
  2. 使用<script>標簽時,type指定為text/x-template,意在告訴瀏覽器這不是一段js腳本,瀏覽器在解析HTML文檔時會忽略<script>標簽內定義的內容。

使用template標簽

template標簽的用法跟script是一樣的,區別在於template標簽不需要設置type,直接設置一個id即可,一般情況下,我們建議使用這種方式來創建模板。如下所示

        <template id="myComponent">
            <div>這是script模板</div>
        </template>

組件快速入門