pubsub-js事件的发布和订阅

Posted on 2020-05-22 10:20  张雪冬前端学习园地  阅读(1000)  评论(0编辑  收藏  举报

pubsub-js事件的发布和订阅

 

 

1.介绍一个优秀的js订阅事件和发布事件的库,通常用于组件与组件之间的传值

// 安装使用

npm i pubsub-js

yarn add pubsub-js

// 在React中使用

// pages/search/index.js组件


import PubSub from 'pubsub-js'


import Child from '../../components/child/index'


class Index extends React.PureComponent {

    constructor (props) {

        super(props)

        this.state = {}
    }

    publishEvent = () => {

        // 订阅事件
        PubSub.publish('zhangxuedong', '用户密码是:18532620986')


        // 取消某一个事件的发布
        // PubSub.unsubscribe('zhangxuedong')


        // 取消事件事件的腹部
        //PubSub.clearAllSubscriptions()


        // 获取发布的事件名称
        // PubSub.getSubscriptions('zhangxuedong')
    } 

    render () {
        
        <div>
            <Child />
             <button onClick={ this.publishEvent }>点击发布事</button>
        </div>
       
    }
}



// components/child/index组件

import PubSub from 'pubsub-js'


class Index extends React.PureComponent {


    componentDidMount () {

        // 订阅事件,第一个参数是事件名称,第二个参数是传递的数据
        PubSub.subscribe('zhangxuedong', (data, msg) => {
          console.log(data, msg)
        })
    }


    render () {

        return (

            <div>我是子组件</div>
        )
    }
}