iT邦幫忙

2021 iThome 鐵人賽

DAY 10
0
Modern Web

30 天我與 Vue 的那些二三事系列 第 10

Day 10 - 元件的資料傳輸(2)

昨天我們提到了如何透過元件區分出獨立的資料流,但問題來了,如果兩個元件的資料需要互通有無呢?

這時候,便是Props出場的時刻。

原始碼可參考以下code sandbox:

https://codesandbox.io/s/modest-monad-ku0do?file=/src/components/ParentComponent.vue

Props

當我們切分元件的時候,可能會希望能夠Reuse這個元件,並讓這個元件可以根據「外部」傳入的資料來反映出不同的結果,這個時候就需要透過 props 屬性來引用外部的狀態。

我們先建立兩個元件,ParentComponent.vue跟ChildComponent,並在ParenetComponet中引用ChiildComponent。

ParenetComponent:

<template>
  <div id="app">
    <child message="From parent"></child>
  </div>
</template>

<script>
import Child from "@/components/ChildComponent.vue";

export default {
  components: {
    Child,
  },
  name: "app",
};
</script>

ChildComponent:

<template>
  <div>
    <span>Message: {{ message }}</span>
  </div>
</template>

<script>
export default {
  props: {
    message: {
      type: String,
      default: "From child",
    },
  },
};
</script>

我們在父元件中傳入message的值,並在子元件中的props進行接收,便可以讓兩個元件進行資料流的互通。

除此之外,也可以透過v-bind動態綁定父元件中的值,當改變inputbox中的值時,也隨之改變傳入的值。

ParentComponent.vue

<template>
  <div id="app">
    <input v-model="parentMsg" />
    <child :message="parentMsg"></child>
  </div>
</template>

<script>
import Child from "@/components/ChildComponent.vue";

export default {
  components: {
    Child,
  },
  name: "app",
  data() {
    return {
      parentMsg: "parent msg",
    };
  },
};
</script>

ChildComponent:

<template>
  <div>
    <span>Message: {{ message }}</span>
  </div>
</template>

<script>
export default {
  props: {
    message: {
      type: String,
      default: "From child",
    },
  },
};
</script>

成果:
https://ithelp.ithome.com.tw/upload/images/20210925/20128925RR97tArWIB.png

不過要注意的是 →

props 是單項綁定的,當父組件的數據改變時,將其傳給子組件,但子組件不能傳給父組件,這是為了避免無意間修改了父組件的數據,避免數據流變得難以理解

不建議在子組件內改變 props ,因為每次父組件更新時,子組件的 props 會更新為最新值,若要改變使用記得另外宣告一個變量來記錄。

Props 資料型態驗證

Props中還有一個相當實用的功能就是,我們可以指定元件的 props 驗證規則,如果傳入的數據不符合要求Vue會發出警告,這樣對於開發給他人使用組件時非常有用。

例如剛剛的範例中,我們指定傳入ChildComponent中的message資料型態須為String,這時候如果我將整數資料傳入message時會發生甚麼事呢?

parentMsg: 20的結果:
https://ithelp.ithome.com.tw/upload/images/20210925/20128925ZIp7JQQnGR.png

Browser跳出錯誤了,提示我們應該傳入字串而非整數的資料!

以上就是今天的內容,我們明天再見囉~


Hi, I am Grant.

個人部落格 - https://grantliblog.wordpress.com/
個人網站 - https://grantli-website.netlify.app/#/mainpage
我的寫作專題 - https://vocus.cc/user/5af2e9b5fd89780001822db4#


上一篇
Day 9 - 元件的資料傳輸(1)
下一篇
Day 11 - 自訂事件
系列文
30 天我與 Vue 的那些二三事30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言