Last active
October 27, 2018 12:02
-
-
Save loveyunk/1e0cc1d071f57bb20b329ca94392224f to your computer and use it in GitHub Desktop.
vue global event bus
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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