〖Vue〗小知识-实战项目中全局状态组件通信-EventBus

203 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

通过前文对 Vue 周边的一些学习, 以及一个小实战练手项目总结: 配置请求跨域处理 和 Swiper 轮播图的应用-及组件化单独分离出来(多个页面会用到). 本文 Vue 项目实战中的 EventBus 组件通信, 作下总结:

Vue EventBus

Vuebus 进行非父子组件的传值($emit / $on)

1. module 文件夹中建立 bus.js

在 bus.js 中输入如下代码:

这样通过 Vue 实例化一个单独的额外的 Vue实例, 用来存储各个组件间的状态公用问题:

/// src/module/bus.js
import Vue from 'vue'
export default new Vue()

2. 将 bus.js 引入到 main.js 中

data:{} 中返回这个 bus

/// src/main.js

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

import router from './router'

import store from './store'
/// 这里引入 EventBus
import bus from './module/Bus'

import axios from 'axios'
Vue.prototype.$http = axios

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  data: {
    bus,
  },
  router,
  store,
  components: { App },
  template: '<App/>',
})

3. 在详情页中 $emit 发送数据

/// src/pages/detail.vue
<script>
  export default {
    data(){
      return {
        movie:{
          cover:{}
        }
      }
    },
    created(){
      var id = this.$route.params.id;
      this.$http.get("/mz/v4/api/film/"+id,{
        params:{
          __t:new Date().getTime()
        }
      }).then((res)=>{
        this.movie = res.data.data.film;
        this.$root.bus.$emit("moviename", this.movie.name); /// 这里使用 EventBus 进行通信
      })
    }
  }
</script>

4. 然后在需要用到上面这些数据的组件内 使用 $on 接收数据

<script>
  export default {
    props: ['toggle'],
    data(){
      return {
        title: "XXX看电影",
        city: "北京"
      }
    },
    created(){
      this.$root.bus.$on("curctname",(msg)=>{
        this.$refs.name.innerHTML=msg;
      })
      this.$root.bus.$on("moviename",(name)=>{
        this.title = name;
      })
      this.$root.bus.$on("logintitle",(name)=>{
        this.title = name;
      })
      this.$root.bus.$on("cityname",(city)=>{
        this.city=city
      })
      this.$router.beforeEach((to,from,next)=>{
        this.changetitle(to.path);
        next();
      })
    },
    methods:{
      changetitle(path){
        switch(path){
          case "/city":this.title = "选择城市"; break;
          case "/login":this.title = "请登陆"; break;
          default:this.title="XX看电影";
        }
      }
    }
  }
</script>