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>
相关推荐
前端之虎陈随易5 小时前
编程语言级别的Skill市场,AI Agent 的未来形态
前端·vue.js·人工智能·typescript·node.js
一路向北he5 小时前
字节钢铁军团--“提供情境,而非控制”
java·开发语言·前端
kyriewen5 小时前
豆包和千问同时关了智能体,我用它们搭的 3 个自动化全废了——迁移方案整理
前端·javascript·ai编程
前端一小卒6 小时前
我用 TypeScript 从零手写了一个 Claude Code,然后发现它的核心只有 30 行
前端·agent
大圣编程7 小时前
Python中continue语句的用法是什么?
开发语言·前端·python
yuhaiqiang7 小时前
随手 vibecoding 的浏览器插件已经 6000 多次下载,聊聊他的产品设计
前端·后端·面试
之歆8 小时前
Vue商品详情与放大镜组件
前端·javascript·vue.js
再吃一根胡萝卜9 小时前
如何把小米 MiMo 接入 CodeBuddy,打造私有 Agent
前端
负责的蛋挞10 小时前
异步HttpModule的实现方式
java·服务器·前端