Vue學習系列(二)——組件詳解

前言

上一篇初識Vue核心中,咱們已經熟悉了vue的兩大核心,理解了Vue的構建方式,經過基本的指令控制DOM,實現提升應用開發效率和可維護性。而這一篇呢,將對Vue視圖組件的核心概念進行詳細說明。html

什麼是組件呢?vue

組件能夠擴展HTML元素,封裝可重用的HTML代碼,咱們能夠將組件看做自定義的HTML元素。數組

爲何要用到組件呢?瀏覽器

爲了可重用性高,減小重複性開發,讓咱們能夠使用獨立可複用的小組件來構建大型應用。app

 

基本

1、組件註冊ide

1.經過Vue.extend()建立,而後由component來註冊函數

// extend 建立組件
var MyComponent = Vue.extend({ template: '<div>A custom component!</div>' }); // component註冊 組件
Vue.component('my-component', MyComponent);//使用到了 extend 建立的組件
var vm = new Vue({ el: '#app', data: { } })

說明ui

  • 1. Vue.extend()是Vue構造器的擴展,調用Vue.extend()建立的是一個組件構造器。 
  • 2. Vue.extend()構造器有一個選項對象,選項對象的template屬性用於定義組件要渲染的HTML。 
  • 3. 使用Vue.component()註冊組件時,須要提供2個參數,第1個參數時組件的標籤,第2個參數是組件構造器。 
  • 4. 組件應該掛載到某個Vue實例下,不然它不會生效。

extend 是構造建立一個組件的語法器,你給它參數 他給你建立一個組件, 而後這個組件,你能夠做用到Vue.component 這個全局註冊方法裏, 也能夠在任意vue模板裏使用組件this

var demo= Vue.extend({ 
…. 
}) 
Vue.component(‘demo’,demo)spa


 可見上邊的定義過程比較繁瑣,也能夠不用每次都調用兩個,能夠直接用 Vue.component 建立 ,也能夠取組件 例以下

var demo= Vue.component(‘demo’)

2.全局註冊

若是咱們定義了多個 vue實例,咱們均可以使用這一個組件

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

//注意要在vue實例以前去定義,否則渲染頁面的時候,會報錯 // 定義一個名爲 myComponent 的新組件
 Vue.component(' myComponent ', { template: ` <div id=" my-component ">
                 <p>2018 <a href="#">艾三元</a> - Hosted by <a href="#" style="font-weight: bold">Coding Pages</a></p>
                 <p>
                     <a href="#">京ICP備00000000號</a>
                 </p>
             </div> `, data () { return { message: 'hello world' } } }) var app = new Vue({ el: '#app',//沒錯,vue實例所定義的DOM元素就是這個,超過了這個區域,定義的組件會無效
 data: { }, }) </script>

3.局部註冊

表示只有在當前頁面的app元素內使用

var app = new Vue({ el: '#app', data: { }, components: { 'my-component': {//這個就是咱們局部組件的名字 在頁面內使用 <my-component></my-component>
 template: ` <ul class ="contact-list non-style-list">
              <li>
                 <b class ="component">組件</b>: <a href="#">@艾三元</a>
              </li>
              </ul>`,       data () {           return {               message: 'hello world'           }       },       directives:{//自定義局部指令,使用的時候,直接能夠 <my-component v-focus><my-component>
        focus;{           inserted(el){             el.focus();           }         }       } } } })

注意:全局的組件是 component,而 局部的是 components

屬性

    定義了這個組件有哪些可配置的屬性,組件的核心功能也是由它肯定。props最好用對象寫法,這樣能夠針對屬性設置類型,默認值或自定義校驗屬性的值。

<script> export default { name: "PropsDemo", props: { name: String, type: { validator: function(value) { //從父級傳入的 type,它的值必須是指定的 'success', 'warning', 'danger'中的一個,若是傳入這三個之外的值,都會拋出一條警告
        return ["success", "warning", "danger"].includes(value); } }, list: { type: Array, // 對象或數組默認值必須從一個工廠函數獲取
      default: () => [] }, isVisible: { type: Boolean, default: false }, onChange: { type: Function, default: () => {} } }, methods: { handleClick() { // 不要這麼作、不要這麼作、不要這麼作 // this.type = "warning"; // 能夠,還能夠更好
      this.onChange(this.type === "success" ? "warning" : "success"); } } }; </script>  


//用法
<props name='Hello World' //原生屬性
           :type='type' :is-visible="false" :on-change="handlePropChange" :list=[22,33,44] title="Demo"  //原生屬性
           class="test1"   //原生屬性
           :class="['test2']" :style="{ marginTop: '15px' }" //注意:style 的優先級是要高於 style
           style="margin-top: 10px">

通信

艾三元

1、父子通信

1.父向子傳值

語法:在父組件中使用子組件時候,經過如下方式傳遞數據

<child-component v-bind:子組件prop="父組件數據屬性"></child-component>

//定義一個組件,並在vue實例中定義了data選項

var vm = new Vue({ el: '#app', data: { name: 'keepfool', age: 28 }, components: { 'my-component': { template: '#myComponent', props: ['myName', 'myAge'] } } }) 定義一個組件 Vue.component('my-component', { template: ` <div id="myComponent">
              <table>
                <tr>
                  <th colspan="2"> 子組件數據 </th>
               </tr>
            <tr>
                <td>my name</td>
                <td>{{ myName }}</td>
           </tr>
           <tr>
            <td>my age</td>
            <td>{{ myAge }}</td>
           </tr>
     </table>
     </div>`, props: ['foo'],//這裏根據組件的props屬性,來被動接受組件傳遞來的參數
 data () { return { message: 'hello world' } } }) //將父組件數據經過已定義好的props屬性傳遞給子組件:
<div id="app">
    <my-component v-bind:my-name="name" v-bind:my-age="age"></my-component>
</div>

注意:在子組件中定義prop時,使用了camelCase命名法。因爲HTML特性不區分大小寫,瀏覽器會把全部大寫字符解釋爲小寫字符,因此camelCase的prop用於特性時,須要轉爲 kebab-case(短橫線分割命名)。例如,在prop中定義的myName,在用做特性時須要轉換爲my-name。

 2.子向父傳值:自定義事件

1) v-on綁定自定義事件:

每一個 Vue 實例都實現了事件接口,即:$on(eventName) 監聽事件 和  $emit(eventName) 觸發事件

 在父組件中:

<my-component  v-on:child-say="listenToMyBoy"></my-component> //三、父組件經過監聽,來獲取到這個廣播信號 child-say ,而後觸發 listenToMyBoy 方法
<p>Do you like me? {{childWords}}</p> methods: { listenToMyBoy: function (somedata){ //四、incrementTotal 被觸發,獲取到參數 counter 值,執行相應的操做
              this.childWords = somedata } }

在子組件my-component中

<button v-on:click="onClickMe">like!</button>  ////一、子組件內,有一個click,當點擊的時候 觸發 onClickMe 方法
 methods: { onClickMe: function(){ this.$emit('child-say',this.somedata);  //二、方法被觸發之後,向父組件 發送一個信號廣播,並傳遞參數 somedata,名字就是 child-say
 } }

 經過子組件註冊觸發事件,父組件註冊 觸發子組件事件後的方法,傳遞參數,父組件經過監聽子組件的事件,獲取參數,執行響應的變化操做

完整示列

<my-component  v-on:child-say="listenToMyBoy"></my-component> //三、父組件經過監聽,來獲取到這個廣播信號 child-say ,而後觸發 listenToMyBoy 方法
<p>Do you like me? {{childWords}}</p> Vue.component('my-component', { template: '<button v-on:click="onClickMe">like!</button>',   //一、子組件內,有一個click,當點擊的時候 觸發 onClickMe 方法
 methods:{ onClickMe: function(){ this.$emit('child-say',this.somedata);  //二、方法被觸發之後,向父組件 發送一個信號廣播,並傳遞參數 somedata,名字就是 child-say
 } } }) var vm = new Vue({ el: '#app', data: { childWords:'' }, methods:{ listenToMyBoy: function (somedata){ //四、incrementTotal 被觸發,獲取到參數 counter 值,執行相應的操做
              this.childWords = somedata } } })

插槽

 

Vue中的插槽,是組件的一塊模板,由使用父組件提供。簡單的說,就是子組件暴露一個讓父組件傳入自定義內容的接口,這樣可讓使用者更好的拓展組件,進行更豐富的複用和定製化組件。

插槽Slot的三大分類:默認插槽、具名插槽和做用域插槽

1.默認插槽:直接在子組件的標籤內寫入內容便可

//父組件
<template>
    <div class="father">
        <h3>灰色背景這是父組件</h3>
        <child>
            <div class="tmpl">
              <span>1</span>
              <span>2</span>
              <span>3</span>
              <span>4</span>
            </div>
        </child>
    </div>
</template>
//子組件
<template>
    <div class="child">
        <h3>藍色背景這是子組件</h3>
        <slot></slot>
    </div>
</template>

 

 2.具名插槽: 用name屬性來表示插槽的名字,不傳爲默認插槽

//父組件
<template>
  <div class="father">
    <h3>灰色背景這是父組件</h3>
    <child>
      <div slot="header">
        <span>頁頭1</span>
        <span>頁頭2</span>
        <span>頁頭3</span>
      </div>
      <div>   //一個不帶 name 的 <slot> 出口會帶有隱含的名字「default」。
        <span>內容1</span>
        <span>內容2</span>
        <span>內容3</span>
      </div>
      <div slot="footer">    
        <span>頁腳1</span>
        <span>頁腳2</span>
        <span>頁腳3</span>
      </div>
    </child>
  </div>
</template>
//子組件
<template>
  <div class="child">
    // 具名插槽
    <slot name="header"></slot>
    <h3>藍色背景這是子組件</h3>
    // 具名插槽
    <slot></slot>  //一個不帶 name 的 <slot> 出口會帶有隱含的名字「default」。 // 匿名插槽
    <slot name="footer"></slot>
  </div>
</template>

 3.做用域插槽: 在做用域上綁定屬性來將子組件的信息傳給父組件使用,這些屬性會被掛在父組件slot-scope接受的對象上

//父組件
<template>
  <div class="father">
    <h3>灰色背景這是父組件</h3>
    <child>
      <template slot-scope="number">
        <div>
          <span v-for="item in number.data">{{item}}</span>
        </div>
      </template>

    </child>

    <child> 這就是模板 </child>
  </div>
</template>

//子組件
<template>
  <div class="child">

    <h3>藍色背景這是子組件</h3>
    // 做用域插槽
    <slot  :data="data"></slot>
  </div>
</template> export default { data: function(){ return { data: ['one','two','three'] } } }

 注意

 

內置指令v-slot,能夠縮寫爲【#】

 子組件用法保持不變,父組件中

  • slot屬性棄用,具名插槽經過指令參數v-slot:插槽名 的形式傳入,能夠簡化爲 #插槽名
<template #header>
     <div>具名插槽</div>
   </template>
  • slot-scope屬性棄用,做用域插槽經過v-slot:xxx="slotProps"的slotProps來獲取子組件傳出的屬性
<!--做用域插槽-->
   <template #footer="slotProps">
     <div> {{slotProps.testProps}} </div>
   </template>
  • v-slot屬性只能在<template>上使用,但在【只有默認插槽時】能夠在組件標籤上使用
<template v-slot>
     <div>默認插槽</div>
 </template> 

總結

 1.經過上述的描述,關於組件的瞭解有了更加進一步的認識,從組件的建立構造器到組件的組成,進而到組件的使用,已經豐富了多樣式的組件,提升了複用性。

2.從組件的基本使用、組件屬性,以及自定義事件實現父子通信和巧妙運用插槽slot分發內容,進一步的認識到組件在Vue中的核心地位

3.參考資料官方文檔

相關文章
相關標籤/搜索