Skip to content

Commit 1f452c0

Browse files
committed
Add documentation for composition API
1 parent 002dc5a commit 1f452c0

4 files changed

+37
-3
lines changed

Diff for: README.md

+34-1
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ app.use(VueSocketIOExt, socket);
9494

9595
## :rocket: Usage
9696

97-
#### On Vue.js component
97+
#### On Vue.js component using the options API
9898

9999
Define your listeners under `sockets` section, and they will be executed on corresponding `socket.io` events automatically.
100100

@@ -119,6 +119,39 @@ createApp({
119119

120120
**Note**: Don't use arrow functions for methods or listeners if you are going to emit `socket.io` events inside. You will end up with using incorrect `this`. More info about this [here](https://github.com/probil/vue-socket.io-extended/issues/61)
121121

122+
#### On Vue.js component using the Composition API
123+
124+
When using the `setup` option of the Composition API, `this` is not available. In order to use socket.io, two composables can be used. `useSocket()` gives you the same object as `this.$socket` would be. With `onSocketEvent(event, callback)` you can subscribe to a `socket.io` event. Subscription will happen before the component is mounted and the component will automatically unsubscribe right before it is unmounted.
125+
126+
```js
127+
import { useSocket, onSocketEvent } from 'vue-socket.io-extended'
128+
129+
defineComponent({
130+
setup() {
131+
const socket = useSocket();
132+
133+
onSocketEvent('connect', () => {
134+
console.log('socket connected')
135+
});
136+
137+
onSocketEvent('customEmit', (val) => {
138+
console.log('this method was fired by the socket server. eg: io.emit("customEmit", data)')
139+
});
140+
141+
const clickButton = (val) => {
142+
// socket.client is the `socket.io-client` instance
143+
socket.client.emit('emit_method', val);
144+
};
145+
146+
return {
147+
clickButton
148+
}
149+
}
150+
})
151+
```
152+
153+
**Note**: Don't subscribe / unsubscribe from events (via `$subscribe()` / `$unsubscribe` provided by `useSocket()`) directly in `setup()`. Always do this from within a lifecycle hook like `onBeforeMount` or `onBeforeUnmount` or in a method that is called once the component is created. The `onSocketEvent` composable will do this automatically for you. The reason is, that the moment `setup()` is executed the component is not yet instantiated and `$subscribe` /`$unsubscribe` therefore can't bind to a component instance.
154+
122155
#### Dynamic socket event listeners (changed in v4)
123156

124157
Create a new listener

Diff for: dist/vue-socket.io-ext.decorator.esm.js

+1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Diff for: dist/vue-socket.io-ext.esm.js

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)