zoukankan      html  css  js  c++  java
  • pubsub-js事件的发布和订阅

    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>
            )
        }
    }
  • 相关阅读:
    APICloud学习笔记之图片缓存
    正则表达式笔记01
    hahah
    panel 绑定鼠标滚轮事件
    C#无边框窗体移动 将事件绑定到想实现的控件上
    消消看最高分破解
    字符串补齐
    ant android打包--学习第一弹
    Windsock套接字I/O模型学习 --- 第三章
    Lua 垃圾收集机制
  • 原文地址:https://www.cnblogs.com/zxuedong/p/12935603.html
Copyright © 2011-2022 走看看