vue3父子传值

本文详细介绍了在Vue3中如何进行父子组件之间的数据传递。通过使用props接收父组件传递的属性,利用context对象获取attrs、slots以及emit来触发事件。同时,文章还演示了如何创建自定义事件实现子组件向父组件的数据传递,从而完成完整的父子通信流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 第一个参数:props :父组件传递过来的属性会被放到props对象中
  • 第二个参数:context:包含3个属性
  1. attrs:所有的非prop的attribute
  2. slots:父组件传递过来的插槽(这个在以渲染函数返回时会有作用,后面会讲到)
  3. emit:当我们组件内部需要发出事件时会用到emit

现创建一个子组件,然后引用子组件 

绑定自定义属性

//父组件
<header-list :msg="123" ></header-list>

<script>
import headerList from "../components/headerList.vue";
 export default {
components: {headerList },
</script>

在子组件接受,这样父传子就完成了

//子组件
<template>
    <div class=''>
      <span>{{msg}}</span>
    </div>
</template>

<script>
	export default {
		// 通过props 接收父组件传递过来的数据,模板中可以直接使用
		props: ['title'],

		setup(props, context) {
			// setup函数中要使用的话,要接收一下
			console.log(props.title)
        }
</script>

在子组件创建一个自定义事件,比如通过点击事件,通过emits发送绑定自定义事件,和需要发送给父组件的数据

//子组件
<template>
    <div class=''>
      <button @click="send">点击</button>
      <span>{{qwe}}</span>
    </div>
</template>
 
<script>
	export default {
		// 1. 通过第二个参数 context 接收父组件传递过来的方法
		setup(props, context) {
          const send = () => {
            // 通过 context.emit触发父组件的方法,第二个参数为传递的参数,可以传递多个
			context.emit('sendData', 100)
			context.emit('sendData', 100, 'aaa', 'bbb')
          }
          // 导出方法提供给模板使用
          return {
            send 
          }
        }
        // 2. 通过第二个参数 解构 emits 接收父组件传递过来的函数
		setup(props, { emit }) {
          const send = () => {
            // 通过emit触发父组件的方法,第二个参数为传递的参数,可以传递多个
			emit('sendData', 100)
			emit('sendData', 100, 'aaa', 'bbb')
          }
          return {
            send 
          }
        }
	}
</script>

在父组件绑定自定义事件,子传父就完成了

//父组件
<template>
  <div class="home">
    <header-list :qwe="123" @sendData="getData"></header-list>
  </div>
</template>

<script>
import headerList from "../components/headerList.vue";
components: {
	headerList 
}
export default {
	components: {
		message
	}
    setup() {
       const getData = (msg) => {
           //子组件的数据
           console.log(msg)
       }
        // 导出方法提供给模板使用
        return {
          getData 
        }
	}
</script>

props中不同类型的写法 

props: {
	// 基础类型指定
	propA: Number,
	// 指定多个类型
	propB: [String, Number],
	// 指定必传类型
	propC: {
		type: String,
		required: true
    },
    // 带有默认值的数字
    propD: {
		type: Number,
		default: 100
	},
	// 带有默认值的对象
	propE: {
		type: Object,
		// 对象或数组默认值必须从一个工厂函数获取
		default() {
			return { mes: 'lihua'}
		}
	},
	// 自定义验证函数
	propF: {
		validator(value) {
			return ['warning', 'success'].includes(value)
		}
	},
	// 具有默认值的函数
	prorG: {
		type: Function,
		default() {
			return 'default function'
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值