Vue & Laravel:访问和使用 eventHub

Vue & Laravel: Access and use eventHub

在 resources/assets/js/app.js 我创建了 eventHub Vue 实例:

require('./bootstrap');    

var eventHub = new Vue();

Vue.component('todos-list', require('./components/todos/TodoList.vue'));
Vue.component('todos-add', require('./components/todos/TodoAdd.vue'));

const app = new Vue({
    el: '#app'
});

如何在单独 .vue 文件中创建的组件中使用它?

比如我也有两个组件:

当我使用 todos-add 组件(TodoAdd.vue) - 我想更新 todos-list 组件中的数据。如果我很好地理解文档 - 对于组件通信,我们需要使用集中式事件中心。这就是我尝试过的 - 但我收到以下错误:

eventHub is not defined

我猜是因为它是在 app.js 中定义的,但是我如何在单独创建的组件中使用 .vue[=46] =] 个文件?

您收到此错误是因为 eventHub 实际上未在您使用它的地方定义。您必须从 app.js 中导出并在 TodoAdd.vue.

中导入

在 app.js 中:

var eventHub = new Vue()
exports.eventHub = eventHub

在TodoAdd.vue中添加此代码:

<script>
import eventHub from '/path/of/app'
export default {
    template: '#todos-list-template',

这应该使 eventHubTodoAdd.vue 中可用。


已编辑

正如评论所建议的那样,您可以考虑使用 vuex,因为您拥有跨组件使用的数据,而且未来我看到了让它变得更复杂、更多事件处理程序和事件侦听器的机会,这很快就会成为管理的噩梦。

var eventHub = new Vue()

您收到此错误是因为 eventHub 实际上未在您使用它的地方定义。您必须从 app.js 文件中导出它。使用这个

window.eventHub = new Vue()