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跳出错误了,提示我们应该传入字串而非整数的资料!

以上就是今天的内容,我们明天再见罗~


<<:  11 手把手带你安装 APCS 虚拟环境

>>:  [Day 25] Node Event loop 4

YouTube 转换为 MP3

由於 YouTube 没有提供下载服务,人们如何将影片、音乐资源转换成 MP3 以便离线播放呢?接下...

Day 26 - [Android APP] 04-MVVM - Repository与API串接

前几天介绍的 MVVM 架构,可以参考这篇 [[Android APP] 01-架构介绍-MVVM]...

[Day3] 自我必备进化力:找到一面镜子

自信心溃堤 因为没有想像,所以没有了信心 当只有自己,自己就是自己的天花板,我之前的工作习惯是,遇到...

Day 2 python简易语法

在开始学习机器学习之前,我们得先准备好环境,我们使用python来当我们的程序语言,稍微介绍一下py...

I Want To Know React - Context 语法

回顾 Context 在上一章节中,我们介绍了何谓 context。 Context 是一种利用向下...