Vue 通过PubSubJS传递数据

时间:2020-05-01

安装插件

npm install pubsub-js --save

兄弟组件数据传递

完整代码

Son1.vue

<template>
    <div>
        <h3>son1</h3>
        <p>
            兄弟组件发过来的数据:{{msg}}
        </p>
    </div>
</template>

<script>
    import Pubsub from 'pubsub-js';
    export default {
        name: "Son1",
        data: function () {
            return {
                'msg': ''
            };
        },
        created() {
            Pubsub.subscribe('msg',(msgName,msg) =>{
                this.msg = msg;
            });
        }
    }
</script>

<style scoped>

</style>

Son2.vue

<template>
    <div>
        <h3>son2</h3>
        <p>

        </p>
    </div>
</template>

<script>
    import Pubsub from 'pubsub-js';
    export default {
        name: "Son2",
        mounted() {
            Pubsub.publish('msg','来自son2的数据');
        }
    }
</script>

<style scoped>

</style>