Vue&Laravel:访问和使用eventHub

问题描述 投票:1回答:2

在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文件中创建的组件中使用它?

例如,我还有两个组件:

  • 位于/components/todos/TodoList.vue中的todos-list,用于使用vue-resource从服务器端获取数据: <template id="todos-list-template"> <div> <ul v-if="todos.length > 0"> <li v-for="todo in todos"> {{ todo.title }} </li> </ul> <p v-else>You don't hanve any Todos.</p> </div> </template> <script> export default { template: '#todos-list-template', data() { return { todos: {} } }, mounted() { this.$http.get('api/vue/todos').then(function(response) { this.todos = response.data; }); }, methods: { handleAddedTodo: function(new_todo) { this.todos.push(new_todo); } }, created: function() { eventHub.$on('add', this.handleAddedTodo); }, destroyed: function() { eventHub.$off('add', this.handleAddedTodo); } } </script>
  • todos-add位于/components/todos/TodoAdd.vue中,用于使用vue-resource添加(保存)新的“todo”: <template id="todos-add-template"> <div> <form v-on:submit.prevent="addNewTodo()"> <div class="form-group"> <input v-model="newTodo.title" class="form-control" placeholder="Add a new Todo"> </div> <div class="form-group"> <button>Add Todo</button> </div> </form> </div> </template> <script> export default { template: '#todos-add-template', data() { return { newTodo: { id: null, title: this.title, completed: false } } }, methods: { addNewTodo() { this.$http.post('api/vue/todos', { title: this.newTodo.title }).then(function(response) { if (response.status == 201) { eventHub.$emit('add', response.data); this.newTodo = { id: null, title: this.title, completed: false } } }, function(response) { console.log(response.status + ' - '+ response.statusText); }) } } } </script>

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

eventHub未定义

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

laravel vue-component vue-resource vue.js
2个回答
1
投票

您收到此错误是因为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',

这应该使qazxsw poi在qazxsw poi中可用。


编辑

正如评论所暗示的那样,你可以考虑使用eventHub,因为你有跨组件使用的数据,并且向前看我看到让它更复杂的机会,更多的事件处理程序和事件listerners,这很快就会成为管理的噩梦。


0
投票
TodoAdd.vue

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

vuex
© www.soinside.com 2019 - 2024. All rights reserved.