Skip to content

Commit fde50da

Browse files
Add events API change section ($on, $off and $once removal) (#167)
* feat: added events api section * fix: renamed section to Migration Strategy
1 parent 4423af4 commit fde50da

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

src/.vuepress/config.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ const sidebar = {
9494
'migration/functional-components',
9595
'migration/async-components',
9696
'migration/custom-directives',
97+
'migration/events-api',
9798
'migration/data-option',
9899
'migration/filters',
99100
'migration/fragments',

src/guide/migration/events-api.md

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
---
2+
types:
3+
- removed
4+
- breaking
5+
---
6+
7+
# `$on`, `$off` and `$once` methods removal <span v-for="type in $frontmatter.types" class="badge" :key="`type-${type}`">{{ type }}</span>
8+
9+
## Overview
10+
11+
`$on`, `$off` and `$once` instance methods are removed. Vue instances no longer implement the event emitter interface.
12+
13+
## Previous Syntax
14+
15+
In v2, Vue instance could be used to trigger handlers attached imperatively via the event emitter API (`$on`, `$off` and `$once`). This was used to create _event hubs_ to create global event listeners used across the whole application:
16+
17+
```js
18+
// eventHub.js
19+
20+
const eventHub = new Vue()
21+
22+
export default eventHub
23+
```
24+
25+
```js
26+
// ChildComponent.vue
27+
import eventHub from './eventHub'
28+
29+
export default {
30+
mounted() {
31+
// adding eventHub listener
32+
eventHub.$on('custom-event', () => {
33+
console.log('Custom event triggered!')
34+
})
35+
},
36+
beforeDestroy() {
37+
// removing eventHub listener
38+
eventHub.$off('custom-event')
39+
}
40+
}
41+
```
42+
43+
```js
44+
// ParentComponent.vue
45+
import eventHub from './eventHub'
46+
47+
export default {
48+
methods: {
49+
callGlobalCustomEvent() {
50+
eventHub.$emit('custom-event') // if ChildComponent is mounted, we will have a message in the console
51+
}
52+
}
53+
}
54+
```
55+
56+
## 3.x Update
57+
58+
We removed `$on`, `$off` and `$once` methods from Vue instance completely. `$emit` is still a part of the existing API as it's used to trigger event handlers declaratively attached by a parent component
59+
60+
## Migration Strategy
61+
62+
Existing event hubs can be replaced by using an external library implementing the event emitter interface, for example [mitt](https://github.com/developit/mitt).
63+
64+
These methods can also be supported in compatibility builds.

0 commit comments

Comments
 (0)