vue組件

什麼叫組件:

有結構HTML
有樣式CSS
有交互(效果)
行爲
信號量存數據

組件的行爲能夠定製?

經過屬性設置

在Vue中有什麼樣的組件(組件進行分類):

實現基本功能的基礎的組件(最小的元素)
可複用的邏輯組件(業務組件)

頁面組件

頁面上全部的東西全都是組件:造成了組件樹

理解組件的建立和註冊

咱們用如下幾個步驟來理解組件的建立和註冊:html

  1. Vue.extend()是Vue構造器的擴展,調用Vue.extend()建立的是一個組件構造器,而不是一個具體的組件實例。vue

  2. Vue.extend()構造器有一個選項對象,選項對象的template屬性用於定義組件要渲染的HTML。app

  3. 使用Vue.component()註冊組件時,須要提供2個參數,第1個參數時組件的標籤,第2個參數是組件構造器。code

  4. Vue.component()方法內部會調用組件構造器,建立一個組件實例。component

  5. 組件應該掛載到某個Vue實例下,不然它不會生效。htm

組件的使用

須要使用Vue.extend方法建立一個組件,而後使用Vue.component方法註冊組件。Vue.extend方法格式以下:對象

var MyComponent = Vue.extend({
   // 選項...後面再介紹
})

使用Vue.component(tagName, options)方法註冊組件:ip

Vue.component('my-component', {
  // 選項
})

組件在註冊以後,便可在HTML標籤中使用這個組件名稱,像使用DOM元素同樣。作用域

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

下面看一個例子:io

// 定義
var MyComponent = Vue.extend({
    template: '<div>A custom component!</div>'
})

// 註冊
Vue.component('my-component', MyComponent)

// 建立根實例
new Vue({
    el: '#example'
})

局部註冊

你沒必要把每一個組件都註冊到全局。你能夠經過某個 Vue 實例/組件的實例選項 components 註冊僅在其做用域中可用的組件:

var Child = {
  template: '<div>A custom component!</div>'
}
new Vue({
  // ...
  components: {
    // <my-component> 將只在父組件模板中可用
    'my-component': Child
  }
})

父組件和子組件

咱們能夠在組件中定義並使用其餘組件,這就構成了父子組件的關係.

<!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中使用。

組件註冊語法糖

以上組件註冊的方式有些繁瑣,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()。

相關文章
相關標籤/搜索