温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Vue全局事件总线是什么

发布时间:2022-02-25 09:22:39 来源:亿速云 阅读:170 作者:小新 栏目:开发技术

这篇文章主要为大家展示了“Vue全局事件总线是什么”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Vue全局事件总线是什么”这篇文章吧。

全局事件总线,是组件间的一种通信方式,适用于任何组件间通信。

看下面具体的例子。

父组件:App

<template>
    <div class="app">
        <Company/>
        <Employee/>
    </div>
</template>

<script>
import Company from "./components/Company.vue";
import Employee from "./components/Employee.vue";

export default {
    components:{
        Company,
        Employee
    }
}
</script>

<style>
.app{
    background: gray;
    padding: 5px;
}
.btn{
    margin-left:10px;
    line-height: 30px;
    background: ivory;
    border-radius: 5px;
}
</style>

子组件:Company和Employee

<template>
  <div class="company">
      <h3>公司名称:{{name}}</h3>
      <h3>公司地址:{{address}}</h3>
      <button @click="sendMessage">点我发送</button>
  </div>
</template>

<script>
export default {
    name:"Company",
    data(){
        return {
            name:"五哈技术有限公司",
            address:"上海宝山"
        }
    },
    methods:{
        sendMessage(){
            console.log("Company组件发送数据:",this.name);
            this.$bus.$emit("demo",this.name);
        }
    }

}    
</script>

<style scoped>
.company{
    background: orange;
    background-clip: content-box;
    padding: 10px;
}
</style>
<template>
  <div class="employee">
      <h3>员工姓名:{{name}}</h3>
      <h3>员工年龄:{{age}}</h3>
  </div>
</template>

<script>
export default {
    name:"Employee",
    data(){
        return {
            name:"张三",
            age:25
        }
    },
    mounted(){
        this.$bus.$on("demo",(data) => {
            console.log("Employee组件监听demo,接收数据:",data);
        })
    },
    beforeDestroy() {
        this.$bus.$off("demo");
    }
}

</script>

<style scoped>
.employee{
    background: skyblue;
    background-clip: content-box;
    padding: 10px;
}
</style>

入口文件:main.js

import Vue from 'vue';  
import App from './App.vue';

Vue.config.productionTip = false;

new Vue({
  el:"#app",
  render: h => h(App),
  beforeCreate(){ 
    Vue.prototype.$bus = this;
  }
})

父组件App,子组件CompanyEmployee

子组件Company和Employee之间通过全局数据总线进行数据传递。

在main.js中,定义了全局事件总线:$bus

$bus定义在Vue.prototype,因此$bus对所有组件可见,即所有组件可通过this.$bus访问。

$bus被赋值为this,即vm实例,因此$bus拥有vm实例上的所有属性和方法,如$emit$on$off等。

new Vue({
  beforeCreate(){ 
    Vue.prototype.$bus = this;
  }
})

使用全局事件总线

$bus.$on,监听事件。Employee组件中定义了监听事件,监听demo事件;

$bus.$emit,触发事件。Company组件中定义了触发事件,点击按钮执行sendMessage回调,该回调将触发demo事件。

Vue全局事件总线是什么

Vue全局事件总线是什么

以上是“Vue全局事件总线是什么”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue
AI