文章

組件通信:Props

在 Vue 3 中,Props 是用來讓父組件向子組件傳遞數據的機制。它是子組件接收父組件數據的主要方式,讓組件之間能夠進行有效的通信。通過使用 Props,父組件可以向子組件提供必要的數據,而子組件可以根據這些數據進行渲染或執行邏輯。

1. 什麼是 Props?

Props 是父組件傳遞給子組件的自定義屬性,這些屬性通過子組件的 props 來接收。在 HTML 中,類似於標籤的屬性(如 classid),Vue 的 props 允許父組件將數據作為參數傳遞給子組件。子組件會定義需要接收的 props,然後可以在模板或邏輯中使用這些數據。

2. 如何使用 Props

1. 定義並傳遞 Props

在父組件中,我們可以通過像 HTML 屬性一樣的語法傳遞 props 給子組件。子組件需要在 props 中聲明它接收的 props。

範例:

父組件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<div id="app">
  <!-- 傳遞數據給子組件 -->
  <child-component :message="parentMessage" :count="parentCount"></child-component>
</div>

<script>
const app = Vue.createApp({
  data() {
    return {
      parentMessage: 'Hello from the parent component!',
      parentCount: 5
    };
  },
  components: {
    'child-component': {
      props: ['message', 'count'],
      template: `
        <div>
          <p></p>
          <p>Count: 9</p>
        </div>
      `
    }
  }
});

app.mount('#app');
</script>

子組件:

在這個例子中,父組件透過 :message:count 傳遞數據,子組件則透過 props: ['message', 'count'] 接收這些數據,並在模板中顯示出來。

  • :message="parentMessage":這裡使用了綁定語法(:prop="data")將父組件的 parentMessage 傳遞給子組件。
  • 子組件定義了 props,即 messagecount,用來接收來自父組件的數據。

2. 進階的 Props 定義

除了基本的 props 定義之外,Vue 3 還支持更詳細的 props 驗證。你可以定義 props 的數據類型、是否必填,甚至可以設置默認值。

1
2
3
4
5
6
7
8
9
10
props: {
  message: {
    type: String, // 定義數據類型
    required: true // 表示這個 prop 是必填的
  },
  count: {
    type: Number,
    default: 0 // 默認值
  }
}

這樣,Vue 會自動檢查 props 是否符合要求,如果不符合,則會在開發模式下拋出錯誤。


3. 動態傳遞 Props

在 Vue 3 中,可以動態傳遞 props,這意味著你可以根據條件或狀態來改變 props 的值。

範例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<div id="app">
  <child-component :message="dynamicMessage"></child-component>
  <button @click="changeMessage">Change Message</button>
</div>

<script>
const app = Vue.createApp({
  data() {
    return {
      dynamicMessage: 'Initial Message'
    };
  },
  methods: {
    changeMessage() {
      this.dynamicMessage = 'Message has been changed!';
    }
  },
  components: {
    'child-component': {
      props: ['message'],
      template: '<p></p>'
    }
  }
});

app.mount('#app');
</script>

在這個範例中,message 是動態的,當使用者按下按鈕後,changeMessage 方法會改變 dynamicMessage 的值,這會自動更新子組件中的顯示內容。


4. 單向數據流

在 Vue 中,數據是單向流動的,這意味著 props 是父組件傳遞給子組件的,只能由父組件進行更改。子組件不能直接修改從父組件接收到的 props,這是為了保持數據流的可預測性。

如果子組件需要修改數據,應該使用 datacomputed 來處理 props,或通過事件傳遞(emit)來告訴父組件進行數據更改。

處理 Props 的變更

在子組件中,我們可以將傳遞進來的 props 作為基礎數據,再將它複製到內部的狀態中,然後進行修改。

1
2
3
4
5
6
props: ['initialMessage'],
data() {
  return {
    localMessage: this.initialMessage // 將 props 複製到內部數據中
  };
}

這樣做,localMessage 可以在子組件中修改,而不會影響到父組件的 initialMessage


5. Props 的數據變更監聽

子組件可以通過 watch 來監聽 props 的變化,當父組件更新傳入的 props 時,可以執行一些響應邏輯。

範例:

1
2
3
4
5
watch: {
  message(newVal, oldVal) {
    console.log('message changed from', oldVal, 'to', newVal);
  }
}

在這裡,我們監聽了 message prop 的變化,當 message 改變時,watch 會觸發相應的邏輯。


總結

  • Props 是 Vue 中組件間進行通信的主要方式,父組件可以通過 props 向子組件傳遞數據。
  • 子組件必須通過 props 接收來自父組件的數據,並且 props 是單向流動的,子組件不能直接修改它們。
  • Vue 提供了多種方式來處理 props,包括數據驗證、默認值和監聽 props 的變化。
  • 通過這些功能,Vue 的 props 系統能夠有效地實現組件之間的數據共享和交互。
本文章以 CC BY 4.0 授權