Vue.js event bus example
Code for the Medium article on event bus
HTML
<script src="https://unpkg.com/[email protected]"></script>
<div id="app">
<todo-list :todos="todos"></todo-list>
<todo-add></todo-add>
</div>
<template id="todo-list">
<div>
<ul>
<li v-for="todo in todos">{{todo.text}}</li>
</ul>
</div>
</template>
<template id="todo-add">
<form action="#" v-on:submit.prevent="handleAddTodoSubmit">
<input type="text" placeholder="Enter todo text" v-model="text">
</form>
</template>
JavaScript
Vue.component('todo-list', {
props: ['todos'],
template: '#todo-list',
created() {
window.eventBus.$on('todo-add', todo => {
this.todos.push(todo)
})
}
})
Vue.component('todo-add', {
template: '#todo-add',
data() {
return {
text: ''
}
},
methods: {
handleAddTodoSubmit() {
if (this.text != '') {
var todo = {
text: this.text
}
window.eventBus.$emit('todo-add', todo)
this.text = ''
}
}
}
})
window.eventBus = new Vue({})
const app = new Vue({
el: '#app',
data: {
todos: [{
text: 'Working'
}, {
text: 'Check'
}]
}
});