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.子组件的方法(参数)调用,
最后不要忘记将常量返回。

猜你喜欢

转载自blog.csdn.net/qq_43750656/article/details/118895610