【Vue3.x】Props父子组件传值

253 阅读1分钟

1. 声明

以一維數組的方式接收

<script setup lang="ts"> 
    const props = defineProps(['foo']) 
    console.log(props.foo) 
</script>

以字符串的方式接收

<script lang="ts" setup>
    const props = defineProps<{ title: string }>()
</script>

如果父組件傳了多個字符串

<script lang="ts" setup>
    const props = defineProps<{ 
        title: string,
        age: number,
        addrss: string}>()
</script>

以對象的方式接收,既有對象,又有boolean

<script setup lang="ts">
    const props = defineProps({
      name: {
        type: String,
        required: true
      },
      title: {
        type: Number,
           required: false
      },
      status: Boolean
    })
</script>

2. Code

運行時聲明

<script lang='ts' setup>
const props = defineProps({
  child: {
    type:String, // 参数类型
    default: 1, //默认值
    required: true, //是否必传
    validator: value => {
      return value >= 0 // 除了验证是否符合type的类型,此处再判断该值结果是否符合验证
    }
  },
  sda: String, //undefined
  strData: String,
  arrFor: Array
})
</script>

類型聲明1

<script lang='ts' setup>
const props = defineProps<{
  either: '必传且限定'|'其中一个'|'值', // 利用TS:限定父组件传 either 的值
  child?: string|number,
  strData?: string,
  arrFor: any[]
}>();
console.log(props);
</script>

類型聲明2

<script lang='ts' setup>
interface Props {
  either: '必传且限定'|'其中一个'|'值', // 利用TS:限定父组件传 either 的值
  child: string|number,
  sda?: string, // 未设置默认值,为 undefined
  strData: string,
  msg?: string
  labels?: string[],
  obj?:{a:number}
}
const props = withDefaults(defineProps<Props>(), {
  msg: 'hello',
  labels: () => ['one', 'two'],
  obj: () => { return {a:2} }
})
</script>

3. Code

index.vue

<template>
  <el-card class="box-card">
    <PageHeader title="nolan"> </PageHeader>
  </el-card>
  <el-card class="box-card">
    <PageContent :user="user" :configName="configName"> </PageContent>
  </el-card>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import PageHeader from '@/components/common/PageHeader.vue'
import PageContent from '@/components/common/PageContent.vue'

const user = reactive({
  name: 'Tom',
  age: 10,
  address: 'China'
})

const configName = ref('Jeff.co.cheng')
</script>
<style scoped>
.box-card {
  margin: 10px;
  font-size: 14px;
}
</style>

PageHeader.vue

<template>
  <h2>this is header</h2>
  <h2>{{ props.title }}</h2>
</template>
<script setup lang="ts">
const props = defineProps<{ title: string }>()
</script>
<style></style>

PageContent.vue

<template>
  <h2>this is content</h2>
  <h2>{{ props.user.name }}</h2>
  <h2>{{ props.configName }}</h2>
</template>
<script setup lang="ts">
 //接收user對象
 //const props = defineProps(['user'])

//接收多個
const props = defineProps({
  user: {
    name: String,
    age: Number,
    address: String
  },
  configName: String
})
</script>
<style></style>