属性 props
约 504 字大约 2 分钟
2025-08-07
一个组件需要显式声明它所接受的 props
,这样 Vue 才能知道外部传入的哪些是 props
,哪些是透传 attribute
简介
一般在子组件中,使用 defineProps()
定义 Props,它接收一个数组作为参数。
下边的代码中,我们定义了 aaa
和 bbb
两个 props。
Person.vue
import { defineProps } from "vue";
const props = defineProps(["aaa", "bbb"]);
我们可以在模板中使用直接使用 aaa
、bbb
作为数据源。
通过打印 defineProps()
的返回值,我们可以看到返回 aaa
、bbb
两个 Proxy 对象。
如果我们需要在代码中使用这两个参数,我们可以通过函数的返回值来获取这两个对象。
在父组件中,直接使用定义的 aaa
、bbb
来给子组件传递参数:
<person :aaa="personList" bbb="111"></person>
Ts 支持
限制接收参数类型
Person.vue
<script setup lang="ts">
import { defineProps } from "vue";
interface Props {
aaa: PersonInter[];
bbb: string;
}
const props = defineProps<Props>();
</script>
默认值 withDefaults
withdefaults
用于父层组件,没给传递值的时候,prop 需要的一个默认值。
<script setup lang="ts">
interface Props {
aaa: PersonList;
bbb?: string;
}
withDefaults(defineProps<Props>(), {
aaa: () => [{ id: "1", age: 21, name: "zhangsan" }],
});
</script>
对比 vue2 的写法
<script>
export default {
props: {
propA: Number, // 带有默认值的数字
propB: [String, Number], // 多个可能的类型
propC: {
type: String,
required: true, // 必填
},
propD: {
type: Number,
default: 100, // 默认值
},
propE: {
type: Object,
// 对象或数组默认值必须从一个工厂函数获取
default: function () {
return { message: "hello" };
},
},
},
};
</script>
代码案例
App.vue
<template>
<div class="container">
<person ref="ren" :aaa="personList" bbb="111"></person>
</div>
</template>
<script lang="ts" setup>
import { defineOptions, ref, reactive } from "vue";
import Person from "./components/Person.vue";
defineOptions({ name: "App" });
const personList = reactive([
{ id: "1", age: 21, name: "zhangsan" },
{ id: "2", age: 22, name: "lisi" },
{ id: "3", age: 24, name: "wangwu" },
]);
</script>
Person.vue
<template>
<div class="person">
<div>
<div v-for="item in aaa" :key="item.id">
<span> name:{{ item.name }}, age: {{ item.age }} </span>
</div>
</div>
<div>{{ bbb }}</div>
</div>
</template>
<script lang="ts" setup>
import { defineOptions, defineProps } from "vue";
defineOptions({ name: "Person" });
// 接收参数
// defineProps(['aaa', 'bbb'])
const props = defineProps(["aaa", "bbb"]);
console.log(props);
</script>
更新日志
2025/8/24 08:17
查看所有更新日志
e7112
-1于