vue3中父组件向子组件传递参数,核心方案是:父组件用 v-bind 绑定数据,子组件用 defineProps 接收数据(组合式 API 语法)。即:v-bind 传 (父)+ defineProps 收(子)。
步骤:
1.父组件:在使用子组件的标签上,通过 :属性名="数据" 绑定要传递的数据;<Child :数据名="变量"/>
2.子组件:使用 defineProps(Vue3 组合式 API 内置函数,无需导入)声明接收的参数; const props = defineProps({数据名: 类型})
3.子组件使用:直接通过变量名使用父组件传递过来的数据;props.数据名 或模板中直接写 数据名
示例:
1.父组件parent.vue
typescript
<template>
<div class="parent">
<h2>我是父组件</h2>
<!-- 核心:向子组件传参 -->
<!-- 1. 传递普通字符串 -->
<!-- 2. 传递变量/对象/数组,必须加 : -->
<Child
:msg="parentMsg"
:user="userInfo"
:list="hobbyList"
/>
</div>
</template>
<script setup>
// 引入子组件(Vue3 自动注册,无需components)
import Child from './Child.vue'
// 父组件的数据
const parentMsg = '来自父组件的消息'
const userInfo = { name: '张三', age: 20 }
const hobbyList = ['吃饭', '睡觉', '打代码']
</script>
2.子组件child.vue
typescript
<template>
<div class="child">
<h3>我是子组件</h3>
<!-- 直接使用接收的参数 -->
<p>字符串:{{ msg }}</p>
<p>对象:{{ user.name }} - {{ user.age }}</p>
<p>数组:{{ list.join('、') }}</p>
</div>
</template>
<script setup>
// 核心:defineProps 接收父组件传递的参数
// 写法1:简单接收(不校验类型)
// const props = defineProps(['msg', 'user', 'list'])
// 写法2:推荐!带类型校验 + 默认值(更规范)
const props = defineProps({
// 字符串类型,必传
msg: {
type: String,
required: true
},
// 对象类型
user: {
type: Object,
default: () => ({}) // 默认空对象
},
// 数组类型
list: {
type: Array,
default: () => [] // 默认空数组
}
})
// 在 JS 中使用传递的数据:props.xxx
console.log('父组件传递的msg:', props.msg)
console.log('父组件传递的user:', props.user.name)
</script>