Skip to content

Instantly share code, notes, and snippets.

@loveyunk
Last active October 27, 2018 12:02
Show Gist options
  • Save loveyunk/1e0cc1d071f57bb20b329ca94392224f to your computer and use it in GitHub Desktop.
Save loveyunk/1e0cc1d071f57bb20b329ca94392224f to your computer and use it in GitHub Desktop.
vue global event bus
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Vue Event Bus</title>
</head>
<body>
<div id="app">
<my-component></my-component>
<p>parent: {{message}}</p>
</div>
<script src="https://vuejs.org/js/vue.js"></script>
<script>
const EventBus = new Vue();
Object.defineProperties(Vue.prototype, {
$bus: {
get: function () {
return EventBus
}
}
});
Vue.component('my-component', {
template: `<button @click="handleClick">click</button>`,
methods: {
handleClick () {
this.$bus.$emit('on-event', 'some message');
}
}
});
new Vue({
el: '#app',
data: {
message: 'hello vue'
},
created () {
this.$bus.$on('on-event', val => {
this.message = val;
});
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment