1. props 使用方式一
父组件
<template>
<div class="about">
<!-- 使用自定义组件 -->
<CustomComponent :aaa="data" bbb="我是来自父组件的数据2" ></CustomComponent>
</div>
</template>
<script setup lang="ts">
// 引入自定义组件
import CustomComponent from "@/components/CustomComponent.vue";
import { ref } from "vue";
const data = ref('我是来自父组件的数据')
</script>
子组件
可以直接使用 defineProps 接受父组件传递过来的参数
<template>
<div>
我是自定义组件
<!-- 使用父组件传递过来的参数 -->
<div>{{ aaa }}</div>
<div>{{ bbb }}</div>
</div>
</template>
<script setup>
// 接受父组件传递的参数
const props = defineProps(['aaa', 'bbb'])
console.log(props.foo)
</script>
<style lang="scss" scoped>
</style>
2. props 使用方式二 限制接收类型
父组件
<template>
<div class="about">
<!-- 使用自定义组件 -->
<CustomComponent :aaa="data" :bbb="{ message: 'dddd' }" :ccc="100"></CustomComponent>
</div>
</template>
<script setup lang="ts">
// 引入自定义组件
import CustomComponent from "@/components/CustomComponent.vue";
import { ref } from "vue";
const data = ref('我是来自父组件的数据')
</script>
子组件
<template>
<div>
我是自定义组件
<!-- 使用父组件传递过来的参数 -->
<div>{{ aaa }}</div>
<div>{{ bbb }}</div>
<div>{{ ccc }}</div>
</div>
</template>
<script setup>
// 接受父组件传递的参数
const props = defineProps({
aaa: String,
// 接收多种类型
ccc: [String, Number],
// 对象或数组的默认值
// 必须从一个工厂函数返回。
bbb: {
type: Object,
default() {
return { message: 'hello' }
},
// 是否比传
required: true
}
})
</script>
<style lang="scss" scoped></style>