Vue3中父子组件传值以及方法调用

  • 子组件接受父组件传的值
    子组件通过生命props属性来接收父组件传递的值
//子组件
<div>{{msg}}</div>

export default {
	name:"child",
	props:{
		msg:{
			type:String,
			required:true,
			default:""
		}
	},
	setup(props,context){
		return {
			msg:props.msg
		}
	}
}

通过在子组件标签声明属性的方式传值,属性的名需要和子组件props中的属性名一致

//父组件
<child :msg="msg"><child>

export default {
	name:"parent",
	components:{child},
	props:{
	},
	setup(props,context){
		const msg = ref("父组件中的值")
		return {
			msg
		}
	}
}
  • 子组件调用父组件的方法
//子组件
export default {
	name:"child",
	props:{
		msg:{
			type:String,
			required:true,
			default:""
		}
	},
	setup(props,context){
		const callParentMethod = ()=>{
			context.emit("print","这是参数")
		}
		return {
			msg:props.msg,
			callParentMethod
		}
	}
}

子组件调用父组件方法需要通过context对象的emit方法,传入要调用的父组件的方法名以及参数,同时在父组件中的子组件标签声明@xxxx的冒泡方法

//父组件
<child :msg="msg" @print="print"><child>

export default {
	name:"parent",
	components:{child},
	props:{
	},
	setup(props,context){
		const print = (param)=>{
			console.log("子组件调用了父组件的方法,参数是:",param)
		}
		const msg = ref("父组件中的值")
		return {
			msg,
			print
		}
	}
}
  • 父组件调用子组件的方法
//父组件
<child :msg="msg" @print="print" ref="RefCid" ><child>

export default {
	name:"parent",
	components:{child},
	props:{
	},
	setup(props,context){
		//这个常量名要和子组件的ref属性一致
		const RefCid = ref()
		const callChildFun = ()=>{
			RefCid.value.fun(1)
		}
		const msg = ref("父组件中的值")
		return {
			msg,
			callChildFun,
			RefCid
		}
	}
}
//子组件
export default {
	name:"child",
	props:{
		msg:{
			type:String,
			required:true,
			default:""
		}
	},
	setup(props,context){
		const callParentMethod = ()=>{
			context.emit("print","这是参数")
		}
	
		const fun = (param) => {
			console.log("子组件的方法被父组件调用了 参数是:",param)
		}

		return {
			msg:props.msg,
			callParentMethod,
			fun
		}
	}
}

父组件调用子组件的方法需要在子组件标签中声明ref属性,同时调用ref()函数创建一个常量,这个常量名要和ref属性的值一致,通过xxx.value.子组件的方法(参数)调用,
最后不要忘记将常量返回。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值