iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 16
2
自我挑戰組

前端新手筆記-Vue.js系列 第 16

Day16 Vue Component(元件) props、emit介紹

本文同步發表於Andy's Blog

前言

昨天認識了Component特性後,我們今天要來介紹Component之間如何傳遞資料

元件溝通方式

元件與元件之間的溝通方式主要有下面幾種
1.props in, emit out
2.event bus
3.$parent、$children
4.Vuex

我們今天主要會專注在propsemit這一種最常用的方式做介紹,而其餘內容將在日後慢慢介紹。

props介紹與使用

  • 用途:父層元件若要將內容傳遞進去子層元件就需要用到props這個屬性。
  • 是一個陣列型態
  • 寫法:v-bind:props-in="msg",其中,props-in是自定義屬性、msg是傳入的內容
    命名注意:HTML 屬性需要使用 kebab-case ,全小寫並使用分隔符號( - )來設定
    如:props-in 參考資料
    圖解:
    https://ithelp.ithome.com.tw/upload/images/20200718/20114645Pg4S1Ksvsn.png
  • 為何需要props屬性?
    還記得,我們昨天有提到元件內的data必須是function型式,確保每個子元件資料的獨立性嗎?正因為這樣,我們也不能透過父元件直接修改子元件內容,因此父元件才需要用到props這個屬性,來將外層資料傳遞進去子元件中。

範例:練習連結
HTML部分

<div id="app">
    <h1>{{msg}}</h1>  //取得實體內資料:Msg of Parent!
    <hr>
    <my-component v-bind:parent-msg="msg"></my-component>  
    //透過自定義屬性:`parent-msg`,將實體內資料:Msg of Parent!傳入元件中
</div>

JavaScript部分

 //x-template
 <script type="text/x-template" id="my-component">
    <div class="component">
      <div> ParentMsg: {{ parentMsg }} </div>   
      <div> ChildMsg: {{ msg }} </div>      
    </div>
  </script>

  <script>
 //global register
 Vue.component('my-component', {
      props: ["parentMsg"],
      template: '#my-component',
      data: function () {
        return {
          msg: 'Msg of Child!'
        }
      }
    });

    // Vue instance
    new Vue({
      el: '#app',
      data: {
        msg: 'Msg of Parent!'
      }
    });
    </script>

圖解:
https://ithelp.ithome.com.tw/upload/images/20200718/20114645rQ1EFZEY1O.png
畫面如下


利用props傳入靜態屬性、動態屬性

  • 靜態傳入寫法:不需要加入v-bind
    寫法:props-in="靜態傳入",會傳入純文字 (註:props-in是自定義名稱)
  • 動態傳入寫法:需要加入 v-bind
    寫法:v-bind:props-in="動態傳入" 或是 :props-in="動態傳入"(註:冒號不能省略)
    範例: 練習連結
<div id="app">
    <hr>
    <my-component parent-msg="靜態傳入"></my-component>
    <my-component :parent-msg="msg"></my-component>
  </div>
  <script type="text/x-template" id="my-component">
    <div class="component">
      <div> ParentMsg: {{ parentMsg }} </div>       
    </div>
  </script>

圖片如下:


emit介紹

  • 目的:當我們今天子元件內容要將資料傳遞到父元件時,就需要使用emit這個屬性。
  • 寫法:
    1.元件Template上 => 綁定觸發事件updateText
    2.Component內層透過this.$emit觸發外層selfUpdate事件
    3.元件HTML中前面是內層自定義事件(update),後面是外層自定義事件(selfUpdate)
  //HTML部分  
  <component @update="selfUpdate"></component>
 //JS部分
 Vue.component('my-component', {
      template: `<div>
                  {{ parentMessage }}
                  <input v-model="message">
                  <button @click="updateText">Update</button>
                </div>`,
        methods: {
        updateText() {
                      //事件名稱 //value =>this.message是指子層的噢!
          this.$emit('update', this.message); 
        }
      }
      
   new Vue({
      methods: {
        selfUpdate(val) {
          this.message = val;
        }
      }
    });
})
  • 備註:會需要使用emit來觸發外層事件,其實是props單向資料流關係,關於這個特性,會在明天介紹props使用注意上再來介紹喔!

範例:練習連結
HTML部分

<div id="app">
    <p>Parent: {{ message }}<input v-model="message"></p>
       <hr>
    <p>
  Child:
  <my-component :parent-message="message" @update="selfUpdate"></my-component>
    </p>
</div>

說明:我們在my-component上,自定義一個update事件,當子元件update事件觸發時,則會同時觸發父元件selfUpdate事件
JavaScript部分

   Vue.component('my-component', {
      template: `<div>
                  {{ parentMessage }}
                  <input v-model="message">
                  <button @click="updateText">Update</button>
                </div>`,
      props: {
        parentMessage: String //字串型別
      },
      data() {
        return {
          message: this.parentMessage
        }
      },
      methods: {
        updateText() {
                      //事件名稱 //value =>this.message是指子層的噢!
          this.$emit('update', this.message); 
        }
      }
    });

    new Vue({
      el: '#app',
      data: {
        message: 'hello'
      },
      methods: {
        selfUpdate(val) {
          this.message = val;
        }
      }
    });

圖解說明:
https://ithelp.ithome.com.tw/upload/images/20200719/20114645VVCOxHda5F.png

結論

這就是我們常講的props in, emit out的由來
1.props口訣:前面是屬性,後面是值
2.emits口訣:元件內this.emit推,外層接收 ; 元件HTML中前內(事件),後外(事件)

參考資料


上一篇
Day 15 Vue Component(元件) 介紹、建立方式、特性
下一篇
Day17 Vue Component(元件) - props使用注意細項(1)
系列文
前端新手筆記-Vue.js30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言