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>
相关推荐
excel2 小时前
为什么 super 中能接收到 resolve 和 reject?
前端
Flynt3 小时前
AI 生成的界面,能放心点吗?我把 Google A2UI 的三层防线拆开测了一遍
前端·google·agent
前端混子4 小时前
我用 AI 做了个「禾月小历」,一套代码跑微信小程序和 H5
前端
IT_陈寒5 小时前
Java实战技巧总结:当你的finally块没有执行时会发生什么?
前端·人工智能·后端
小帅不太帅5 小时前
一年一次黑五,为了买软件真省钱,我做了个开源小站
前端·人工智能·github
JavaGuide7 小时前
刚刚,阿里版 Codex 上线了匿名模型 HungerG,无限 Token!
前端·后端
zhanlang02177 小时前
HTML 零基础入门到企业实战全套教程【第九章 9.3】移动端 HTML 基础适配入门
前端·html
用户69371750013847 小时前
AI 帮我写了大半年的代码,我却越来越不会写代码了
前端·后端·github
skywalk81637 小时前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness
彭亚川Allen8 小时前
从零手搓 RAG:用 Elasticsearch 存储与检索向量
前端·后端·面试