Props

Props是什麼?

Props是組件的自定義屬性,父組件可以通過這些屬性向子組件傳遞數據。子組件需要顯式聲明它期望接口的props,然後就可以像使用內部數據一樣使用它們。

核心特性:

  • 單向數據流:數據只能從父組件流向子組件,子組件不能直接修改props
  • 聲明性:子組件必須聲明它要接受的props
  • 任意類型:可以傳遞字符串、數字、數組、對象、函數等任何類型

我們定義一個可給子組件接受的屬性

<template>
    <Person title="IT知識一享"/>
</template>
  • 我們可以直接使用字符串數組式聲明
<template>
  <div class="person">
    {{ titleProps.title }}
  </div>
</template>

<script lang="ts" setup>
import { defineProps } from 'vue';
  const titleProps = defineProps(['title'])
</script>

Vue3中的Props_IT


對象式聲明

  • 上述字符串數組式聲明不推薦使用,因為無法指定類型和默認值,對象式聲明式功能完整,可以指定類型、默認值、校驗規則
<script lang="ts" setup>
    import Person from './components/Person.vue'
    import { reactive } from 'vue';
    import {type persons } from './types';

    const personList = reactive<persons>([
        {name:'IT知識一享',age:18,id:66668888},
        {name:'IT知識一享2',age:28,id:66669999},
        {name:'IT知識一享3',age:38,id:66660000},
    ])
</script>

我們在父組件定義了一些數據,這個數組結構我們在ts中定義過了,和上一小節一樣的,reactive<>,這個是一種結合泛型的寫法

  • 傳遞Props

在父組件中,我們使用v-bind,或者簡寫:向子組件傳遞數據

<template>
    <Person :PersonPros="personList"/>
</template>
  • 這樣我們就能在子組件進行接受了
<script lang="ts" setup>
import { defineProps } from 'vue';
  const titleProps = defineProps(['PersonPros'])
</script>
  • 我們使用v-for將數組遍歷展示出來
<template>
  <div class="person">
    <ul>
      <li v-for="item in titleProps.PersonPros" :key='item.id'>{{ item.name }} || {{ item.age }} || {{ item.id }}</li>
    </ul>
  </div>
</template>

Vue3中的Props_默認值_02


  • 子組件在接受參數的時候,最好可以限制類型
<script lang="ts" setup>
import { defineProps } from 'vue';
import {type persons} from '@/types';

  const titleProps = defineProps<{PersonProps:persons}>()
</script>

這樣當父組件傳的不是PersonProps的時候就會報錯

  • 出來限制類型,我們也可以添加可選項和默認值
<script lang="ts" setup>
import { defineProps,withDefaults } from 'vue';
import {type persons} from '@/types';

  const titleProps = withDefaults(defineProps<{PersonProps?:persons}>(),{PersonProps:()=>[
    {name:'默認值',age:0,id:11111111}]
  })
</script>

withDefaults可以添加默認值,當父組件沒有傳遞給子組件任何東西的時候,就會使用默認值;PersonProps?這個前面説過了,這個是個可選項,父組件傳不傳都可以

Vue3中的Props_數據_03