首页 > 解决方案 > vue js通过全局事件总线传递数据不起作用

问题描述

使用 vue cli,我创建了一个带有两个嵌套组件的简单 vue 应用程序。我想通过单击组件 1 中的 h1 标签在它们之间传递数据(更结构化的方法建议使用 vuex,但这是一个非常简单的应用程序,用于传递简单数据用于测试)。

单击 h1 我收到一个错误,但我不明白这一点。错误说

[Vue warn]: Error in event handler for "titleChanged": "TypeError: Cannot read property 'apply' of undefined"

(found in <Root>)

我的代码如下

main.js

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

Vue.config.productionTip = false
Vue.prototype.$http = Axios

export const bus = new Vue();

new Vue({
  render: h => h(App),
}).$mount('#app')

应用程序.vue

<template>
  <div>
    <comp-1 v-bind:title="title"></comp-1>
    <comp-2 v-bind:title="title"></comp-2>
  </div>
</template>

<script>
  import comp-1 from './components/Comp-1.vue'
  import comp-2 from './components/Comp-2.vue'

  export default {
    components: {
      'comp-1': comp-1,
      'comp-2': comp-2
    },
    data() {
      return {
        title: "my title"
      }
    }
  }
</script>

<style scoped>

</style>

comp-1.vue

<template>
    <header>
        <h1 v-on:click="changeTitle">{{ pTitle }}</h1>
    </header>
</template>

<script>
    import {bus} from '../main'

    export default {
        props: {
            title: {
                Type: String
            }
        },
        data() {
            return {
                pTitle: ''
            }
        },
        created: function() {
            this.pTitle = this.title
        },
        methods: {
            changeTitle: function() {
                this.pTitle = 'I have changed my title!'
                bus.$emit('titleChanged', this.pTitle)
            }
        }
    }
</script>

<style scoped>

</style>

comp-2.vue

<template>
    <footer>
        <p>{{ title }}</p>
    </footer>
</template>

<script>
    import {bus} from '../main'

    export default {
        props: {
            title: {
                Type: String
            }
        },
        data() {
            return {
                pTitle: ''
            }
        },
        created() {
            this.pTitle = this.title;

            bus.$on('titleChanged'), (data) => {
                this.title = data
            }
        }
    }
</script>

<style scoped>

</style>

标签: vuejs2emit

解决方案


在创建 comp-2 组件时,事件处理程序有错误

像这样改变它:

bus.$on("titleChanged", data => {
  this.title = data;
});

推荐阅读