What does vue-happy-bus do
Vue-happy-bus is a subscription/publishing plug-in based on the VUE implementation.
We usually use the new Bus() approach to do an event broadcast when communicating between non-parent components. A disadvantage is that this method does not automatically destroy, so you need to do Bus.$off(‘event name’, fn) in the destroyed cycle to avoid repeated callbacks.
The resulting redundant code is:
- The $on callback must be a named function. Can’t be simple
Bus.$on('event name', () => {})
Anonymous functions are used as callbacks, so you need to put the callback function inmetheds
In theAdditional statement
- in
destroyed
Life cycle to destroy the listener of the event.
I just want to listen for a header button click in a route.
So the wheel was made.
It mainly solves the problem that the callback function is executed multiple times when the communication between non-parent and child components is repeatedly bound and cannot be destroyed automatically.
In general, he can get youlazy
Tools for writing less code.
The installation
- NPM recommended
npm
“, so that you can followwebpack
Configure to choose how to package.
npm i -D vue-happy-bus
Copy the code
- CDN
<html>
<script src="https://unpkg.com/vue-happy-bus/dist/happy-bus.min.js"></script>
</html>Copy the code
How to use
import BusFactory from 'vue-happy-bus' export default { data () { return { bus: BusFactory(this) // After binding this to BusFactory, return a bus, $on this.bus.$on('event name', 'event name'); $once('event name', $emit) => {// do something}) () => {// do something}) BusFactory.$emit('event name', 'parameter ')}}Copy the code
attribute
Bus contains only four methods:
- $on
- $off
- $emit
- $once
They are derived from new Vue() and are used in exactly the same way as Vue.
PR
Look forward to and welcome your PR. But be sure to follow the Standard code style specification. You only need to submit the source code in the SRC directory. You do not need to submit the code after build
License
MIT
Copyright (c) 2017-present, tangdaohai