nolde/vue-plugin-events(新しいタブで開きます)
主要言語: JavaScript
Simple global event bus for Vue.js applications with automatic subscription control.
- star 数
- 5
- watcher 数
- 1
- fork 数
- 0
- issue 数
- 13
- 最終更新
- 2022/12/09
主要言語: JavaScript
Simple global event bus for Vue.js applications with automatic subscription control.
Simple global event bus for Vue.js applications with automatic subscription control. Zero dependencies.
npm install --save vue-plugin-events
import Vue from 'vue' import VueEvents from 'vue-plugin-events' Vue.use(VueEvents)
<!-- Include after Vue --> <!-- Local files --> <script src="vue-plugin-events/dist/vue-plugin-events.umd.js"></script> <!-- From CDN --> <script src="https://cdn.jsdelivr.net/npm/vue-plugin-events"></script>
The plugin will automatically subscribe a component to events defined within its body. This is achieved using a new section named events. When your component is destroyed, so are any listeners that have been automatically created.
The handlers follow a pattern similar to component watch section.
// MyComponent.vue export default { data: () => ({ myValue: 'anything' }), methods: { doSomething (arg) { /*...*/ } }, events: { // will execute method `doSomething` when event named `someEvent` is emitted someEvent: 'doSomething', // will fire when event named `someHandledEvent` is emitted someHandledEvent (v) { this.doSomething(v) }, // will fire when event named `immediateEvent` is emitted, and as // soon as the component is loaded and this section is evaluated, // much like `immediate` option from watchers immediateEvent: { immediate: true, handler (v) { this.doSomething(v) } }, // will fire when a `justOnceEvent` is fired, and then won't fire again; // may fire twice if combined with `immediate` justOnceEvent: { once: true, handler (v) { console.log('arg is', v) } } } }
Every component will be inject with an instance of $event, which allows the developer to emit events into the application-wide event bus. Any components listening to the emitted event will be triggered. More details can be seen in the API section below.
The methods exposed by $event below are basically the same as normal event methods in a Vue component, but instead of having only the parent component as a listeners, any component can subscribe to any events.
// AnyComponent.vue export default { // ... methods: { onSomething () { this.$events.emit('someEvent', this.payload) } }, // ... }
{string} eventName[...args]{string | Array<string>} event (array only supported in Vue 2.2.0+){Function} callback{string | Array<string>} event (array only supported in Vue 2.2.0+){Function} callback{string | Array<string>} event (array only supported in Vue 2.2.2+){Function} [callback]ISC © 2019 Ricardo Nolde