事件总线 $bus. 任意组件间传值

1.首先在main.js中配置全局总线 

import Vue from 'vue'

import App from './App.vue'

Vue.config.productionTip = false

new Vue({

  render: h => h(App),

  beforeCreate(){

    Vue.prototype.$bus = this

  }

}).$mount('#app')

2. 全局事件总线首先得被所有组件能看见

<template>
    <div class="app">
        <School/>
        <Student/>
    </div>
</template>

<script>
    import Student from './components/Student'
    import School from './components/School'
    export default {
        name:'App',
        components:{School,Student},
    }
</script>

3. 在Student组件中提供数据给另一个组件(School组件)

<template>
    <div class="student">
        <h2>学生姓名:{{name}}</h2>
        <h2>学生性别:{{sex}}</h2>
        <button @click="sendStudentName">把学生名给School组件</button>
    </div>
</template>

<script>
    export default {
        name:'Student',
        data() {
            return {
                name:'张三',
                sex:'男',
            }
        },
        methods: {
            sendStudentName(){        //提供发送数据
                this.$bus.$emit('hello',this.name)
            }
        },
    }
</script>

4.在School组件中使用事件总线,接收数据。School组件想接收数据,则在School组件中给 $bus绑定事件,事件的回调则留在School组件自身。

<template>
    <div class="school">
        <h2>学校名称:{{name}}</h2>
        <h2>学校地址:{{address}}</h2>
    </div>
</template>

<script>
    export default {
        name:'School',
        data() {
            return {
                name:'工程学院',
                address:'重庆巴南',
            }
        },
        mounted() {
            this.$bus.$on('hello',(data)=>{      //绑定当前事件(这里以hello为例)
                console.log('我是School组件,收到了数据',data)
            })
        },
        beforeDestroy(){        //收尾操作,销毁
            this.$bus.$off('hello')  //$off解绑当前组件所用到的事件
        }
    }
</script>

 

posted @ 2022-07-22 10:33  小成-  阅读(163)  评论(0)    收藏  举报