组件之间如何进行通信
如何将组件A中的数据传递到组件B
- 组件B请求组件A的数据,组件B是事件执行者
- 组件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)