如何进行组件通信

组件之间如何进行通信

如何将组件A中的数据传递到组件B

  1. 组件B请求组件A的数据,组件B是事件执行者
  2. 组件A向组件B推送数据,组件A是事件执行者
    在这里插入图片描述
  • 在方法一中,组件A提供了一个可以访问自身的数据的公共方法,组件B调用这个的方法,就可以拿到数据
  • 在方法二中,组件B对外提供了一个碗,你只要往碗里放东西,组件B就能拿到。
    总结:方法一是主动要数据,方法二是被动接收数据。一种是数据源提供方法,一种是接收者提供方法。
    使用方法一,通过组件传递来实现父子组件间的通信。
class Family {
	#money = 10000
	goShopping(cost) {
		this.#money -= cost
	}
	ToWork(salary) {
		this.#money += salary
	}
	Audit() {
		return this.#money
	}
}
class Couple extends Family {
	money
	constructor() {
		super()
		super.ToWork(10000)
		super.goShopping(1000)
	}
	Audit() {
		return (this.money = super.Audit())
	}
}
new Couple().Audit()

const props = {
	name: "defaultName",
	setName(val:string) {
		this.name = val
	},
	getName() {
		return this.name
	}
}
type Prop={
	name:string,
	setName:(val:string)=>void,
	getName:()=>string
}
function Component(props:Prop) {
	return {
		 ...props
	 }
}

class Child{
	props:Prop
	constructor(){
		// 接收父组件传过来的props
		this.props=Component(props)
	}
}
const c=new Child()
c.props.getName()
c.props.setName('newVal')
console.log(c.props.name)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值