vue3 父组件向子组件传参

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>
相关推荐
JustHappy4 小时前
古法编程秘籍(七):互联网到底是什么?把两台电脑怎么说话搞懂就够了
前端·后端·网络协议
snow@li4 小时前
SEO-文章标题:写文章时候,分类+主标题+大纲+解释 作为标题 / 不点进去也知道全文覆盖什么 / 标题即架构
前端
kyriewen5 小时前
Git Commit 前自动修复代码风格?配置 Husky + lint-staged,从此 CR 只聊逻辑
前端·git·面试
小和尚同志5 小时前
AI 自动化测试探索(一):Playwright MCP
前端·人工智能·aigc
老马识途2.05 小时前
在AI的帮助下理解spring的启动过程
java·前端·spring
徐小夕6 小时前
Loop Engineering 深度解析与实战指南(全网最全)
前端·算法·github
运筹vivo@6 小时前
Python ContextVar 底层机制与内存模型拆解
前端·数据库·python
#麻辣小龙虾#7 小时前
基于vue3.0开发一款【固废与废气运维管理系统】(支持源码)
前端·vue.js·vue3
Cosolar7 小时前
Docsify零构建文档站完全指南:从快速搭建到企业级部署
前端·开源·github
weixin_471383038 小时前
Taro-02-页面路由
前端·taro