2025-01-03
用于兄弟组件的数据传递。
对发布-订阅模式的实现,借助PubSubJS的第三方包实现。
npm init -y
npm install pubsub-js
工具 - 构建npm
import PubSub from 'pubsub-js'
import PubSub from 'pubsub-js'
Component({
data: {
name: "Tom",
age: 10
},
methods: {
sendData(){
PubSub.publish('myevent', {name: this.data.name, age: this.data.age})
}
}
})
import PubSub from 'pubsub-js'
Component({
data: {
name: '',
age: ''
},
methods: {
},
lifetimes: {
attached(){
PubSub.subscribe('myevent', (msg, data) => {
this.setData({
name: data.name,
age: data.age
})
})
}
}
})