在父组件里面创建一个类实例传递给子组件,这个类实例有一个方法可以push数据到一个数组,然后类里面有一个定时器会去这个数组里面取数据出来消费。子组件push的数据在定时器回调里面看不见,只能看见父组件push的数据。
代码如下:
export class Test {
private queue: number[] = []
private timer: number | null = null
constructor() {
this.timer = setInterval(() => {
if (this.queue.length) {
console.log('pop:', this.queue.shift())
}
}, 1000)
}
push(a: number) {
this.queue.push(a)
console.log('push:', a)
}
}
@Component
struct Children {
@Prop @Require test: Test
build() {
Column() {
Text('我是子组件')
}
}
aboutToAppear(): void {
setInterval(() => {
this.test.push(1)
}, 1000)
}
}
@Entry
@Component
struct Index {
private test: Test = new Test()
build() {
Column() {
Text('我是父组件')
Children({
test: this.test
})
}
}
aboutToAppear(): void {
setInterval(() => {
this.test.push(2)
}, 1000)
}
}
可以看见push日志有1和2,pop只有2。
@Prop装饰器指的是父子单向同步,可以使用@Link(父子双向同步),参考demo: