vue.js publisher and subscriber

Introduction

Like a micro-channel public number, it will regularly push content, and subscribe to all its users will receive the content push

Publish and subscribe effects need to be able to play in the same instance of
$ emit - Posted by
$ on - Statement subscribers
$ once subscribers only subscribe to a message (for example, I subscribe to a public number, it only gave me a push content, I put it to cancel the subscription, will no longer receive follow-up)
$ OFF unsubscribe (all subscribers only accept a message)

Code specific description

/*---------------------------html--------------------------*/
<div id="root">
    <input type="button" @click="fn" :value="num">  //当我点击这个按钮的时候,触发fn事件
</div>
/*---------------------------js--------------------------*/
   new Vue({
        el:"#root",
        data:{
            num:1
        },
        methods:{
           fn(){  //当这个事件触发的时候
                  // 发布一个名字为one的消息。
                  //当它发布这个消息以后,订阅这个消息的订阅者都会被触发
                  //第一个参数是你消息的名字,后面的是传的值
               this.$emit("one",1,2,3,4);
           }
        },
        mounted(){
            // 声明订阅者,订阅了一个名字为one的消息
            this.$on("one",(a,b,c,d)=>{
                this.$off("one");
                console.log(a,b,c,d);
            })
            this.$once("one",()=>{
                console.log(222222222222);
            })
        }
    })

Click the button after the results show :()
Here Insert Picture Description

Published 63 original articles · won praise 6 · views 1226

Guess you like

Origin blog.csdn.net/qq_44163269/article/details/105080292