Gathering detailed insights and metrics for @awamwang/vue-socket.io-extended
Gathering detailed insights and metrics for @awamwang/vue-socket.io-extended
✌⚡ Socket.io bindings for Vue.js and Vuex (inspired by Vue-Socket.io)
npm install @awamwang/vue-socket.io-extended
Typescript
Module System
Node Version
NPM Version
JavaScript (98.24%)
Shell (1.76%)
Verify real, reachable, and deliverable emails with instant MX records, SMTP checks, and disposable email detection.
Total Downloads
675
Last Day
2
Last Week
5
Last Month
8
Last Year
143
MIT License
1,529 Commits
11 Branches
1 Contributors
Updated on Jun 27, 2022
Minified
Minified + Gzipped
Latest Version
0.0.3
Package Id
@awamwang/vue-socket.io-extended@0.0.3
Unpacked Size
36.23 kB
Size
11.33 kB
File Count
10
NPM Version
8.11.0
Node Version
16.15.1
Cumulative downloads
Total Downloads
Last Day
0%
2
Compared to previous day
Last Week
0%
5
Compared to previous week
Last Month
-42.9%
8
Compared to previous month
Last Year
-36.7%
143
Compared to previous year
2
24
Socket.io bindings for Vue.js 2 and Vuex (inspired by Vue-Socket.io)
:warning: The alpha version of v5 (with Vue 3 support) has been released. Your feedback would be appreciated here
'''继承自robil/vue-socket.io-extended,更新依赖,修复socket.io-client问题
$socket.connected
and $socket.disconnected
socket.io
events inside componentssocket.io
eventssocket.io-client
![]() | ![]() | ![]() | ![]() | ![]() |
---|---|---|---|---|
49+ :heavy_check_mark: | 18+ :heavy_check_mark: | 10+ :heavy_check_mark: | 36+ :heavy_check_mark: | 12+ :heavy_check_mark: |
We support only browsers with global usage statistics greater than 1% and due to current Vue 3 limitation - with native Proxy support.
I was using Vue-Socket.io
for few months. I've liked the idea, but the more I used it the more I faced with bugs, outdated documentation, lack of support, absence of tests, and a huge amount of issues :disappointed:. That slowed down development of the product I was working on. So I ended up with a decision to create my own fork with all the desirable stuff (features/fixes/tests/support/CI checks etc). That's how vue-socket.io-extended
was born.
If you'd like to help - create an issue or PR. I will be glad to see any contribution. Let's make the world a better place :heart:
You must have a running Socket.IO server before starting any Vue/Socket.IO project! Instructions on how to build a Node/Socket.IO server can be found here.
3.X
>= 2.X
>= 4.X
(optional)1npm install vue-socket.io-extended@alpha socket.io-client
1import VueSocketIOExt from 'vue-socket.io-extended'; 2import { io } from 'socket.io-client'; 3import { createApp } from 'vue'; 4 5const socket = io('http://socketserver.com:1923'); 6 7const app = createApp({}); 8app.use(VueSocketIOExt, socket);
Note: you have to pass instance of socket.io-client
as second argument to prevent library duplication. Read more here.
1<script src="https://cdn.jsdelivr.net/npm/vue@next/dist/vue.global.min.js"></script> 2<script src="https://cdn.jsdelivr.net/npm/socket.io-client/dist/socket.io.slim.js"></script> 3<script src="https://cdn.jsdelivr.net/npm/vue-socket.io-extended@alpha"></script> 4<script> 5 var socket = io('http://socketserver.com:1923'); 6 var app = Vue.createApp({}); 7 app.use(VueSocketIOExt, socket); 8</script>
Define your listeners under sockets
section, and they will be executed on corresponding socket.io
events automatically.
1createApp({ 2 sockets: { 3 connect() { 4 console.log('socket connected') 5 }, 6 customEmit(val) { 7 console.log('this method was fired by the socket server. eg: io.emit("customEmit", data)') 8 } 9 }, 10 methods: { 11 clickButton(val) { 12 // this.$socket.client is `socket.io-client` instance 13 this.$socket.client.emit('emit_method', val); 14 } 15 } 16})
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
Create a new listener
1this.$socket.$subscribe('event_name', payload => {
2 console.log(payload)
3});
Remove existing listener
1this.$socket.$unsubscribe('event_name');
The $socket.connected
and $socket.diconnected
are reactive. That means you can use them in expressions
1<template> 2 <div> 3 <span>{{ $socket.connected ? 'Connected' : 'Disconnected' }}</span> 4 </div> 5</template>
Or conditions
1<template> 2 <span 3 class="notification" 4 v-if="$socket.disconnected" 5 > 6 You are disconnected 7 </span> 8</template>
Or computed properties, methods and hooks. Treat them as computed properties that are available in all components
To set up Vuex integration just pass the store as the third argument. In a Vue CLI project, you might do this in the src/main.js
file. Example:
1import VueSocketIOExt from 'vue-socket.io-extended'; 2import { io } from 'socket.io-client'; 3import store from './store' 4 5const socket = io('http://socketserver.com:1923'); 6const app = createApp({}); 7 8app.use(VueSocketIOExt, socket, { store });
Mutations and actions will be dispatched or committed automatically in the Vuex store when a socket event arrives. A mutation or action must follow the naming convention below to recognize and handle a socket event.
SOCKET_
prefix and continue with an uppercase version of the eventsocket_
prefix and continue with camelcase version of the eventServer Event | Mutation | Action |
---|---|---|
chat message | SOCKET_CHAT MESSAGE | socket_chatMessage |
chat_message | SOCKET_CHAT_MESSAGE | socket_chatMessage |
chatMessage | SOCKET_CHATMESSAGE | socket_chatMessage |
CHAT_MESSAGE | SOCKET_CHAT_MESSAGE | socket_chatMessage |
Check the Configuration section if you'd like to use a custom transformation.
Check the Migration from VueSocketIO section if you want to keep actions names in UPPER_CASE.
1// In this example we have a socket.io server that sends message ID when it arrives
2// so to get entire body of the message we need to make AJAX call the server
3import { createStore } from 'vuex';
4
5// `MessagesAPI.downloadMessageById` is an async function (goes to backend through REST Api and fetches all message data)
6import MessagesAPI from './api/message'
7
8export default createStore({
9 state: {
10 // we store messages as a dictionary for easier access and interaction
11 // @see https://hackernoon.com/shape-your-redux-store-like-your-database-98faa4754fd5
12 messages: {},
13 messagesOrder: []
14 },
15 mutations: {
16 NEW_MESSAGE(state, message) {
17 state.messages[message.id] = message;
18 state.messagesOrder.push(message.id);
19 }
20 },
21 actions: {
22 socket_userMessage ({ dispatch, commit }, messageId) { // <-- this action is triggered when `user_message` is emmited on the server
23 return MessagesAPI.downloadMessageById(messageId).then((message) => {
24 commit('NEW_MESSAGE', message);
25 })
26 }
27 }
28})
Events can be sent to the Socket.IO server by calling this._vm.$socket.client.emit
from a Vuex mutation or action. Mutation or action names are not subject to the same naming requirements as above. More than one argument can be included. All serializable data structures are supported, including Buffer.
1 actions: { 2 emitSocketEvent(data) { 3 this._vm.$socket.client.emit('eventName', data); 4 this._vm.$socket.client.emit('with-binary', 1, '2', { 3: '4', 5: new Buffer(6) }); 5 } 6 }
Namespaced modules are supported out-of-the-box. Any appropriately-named mutation or action should work regardless of whether it's in a module or in the main Vuex store.
1import { createStore } from 'vuex'; 2 3const messages = { 4 state: { 5 messages: [] 6 }, 7 mutations: { 8 SOCKET_CHAT_MESSAGE(state, message) { 9 state.messages.push(message); 10 } 11 }, 12 actions: { 13 socket_chatMessage() { 14 console.log('this action will be called'); 15 } 16 }, 17}; 18 19const notifications = { 20 state: { 21 notifications: [] 22 }, 23 mutations: { 24 SOCKET_CHAT_MESSAGE(state, message) { 25 state.notifications.push({ type: 'message', payload: message }); 26 } 27 }, 28}; 29 30export default createStore({ 31 modules: { 32 messages, 33 notifications, 34 } 35})
The above code will:
SOCKET_CHAT_MESSAGE
mutation in the messages
moduleSOCKET_CHAT_MESSAGE
mutation in the notification
modulesocket_chatMessage
action in the messages
moduleRequired: ECMAScript stage 1 decorators.
If you use Babel, babel-plugin-transform-decorators-legacy is needed.
If you use TypeScript, enable --experimentalDecorators
flag.
It does not support the stage 2 decorators yet since mainstream transpilers still transpile to the old decorators.
We provide @Socket()
decorator for users of class-style Vue components. By default, @Socket()
decorator listens the same event as decorated method name, but you can use custom name by passing a string inside decorator e.g. @Socket('custom_event')
.
Check the example below:
1<!-- App.vue --> 2<script> 3import { Options, Vue } from 'vue-class-component'; 4import Socket from 'vue-socket.io-extended/decorator'; 5 6@Options({}) 7export default class App extends Vue { 8 @Socket() // --> listens to the event by method name, e.g. `connect` 9 connect () { 10 console.log('connection established'); 11 } 12 13 @Socket('tweet') // --> listens to the event with given name, e.g. `tweet` 14 onTweet (tweetInfo) { 15 // do something with `tweetInfo` 16 } 17} 18</script>
:warning: The current version of Nuxt.js (v2) doesn't support Vue 3 just yet. The section is going to be updated after the initial release. Check v4 for integration with Vue 2 & Next 2
:warning: The current version of Quasar (v1) doesn't support Vue 3 just yet. Beta version is planned for Jan 2021 though, while the final version is expected to be released in Q1. The section is going to be updated after the initial release. Check v4 for integration with Vue 2 & Quasar 1
In addition to store instance, vue-socket.io-extended
accepts other options.
Here they are:
Option | Type | Default | Description |
---|---|---|---|
store | Object | undefined | Vuex store instance, enables vuex integration |
actionPrefix | String | 'socket_' | Prepend to event name while converting event to action. Empty string disables prefixing |
mutationPrefix | String | 'SOCKET_' | Prepend to event name while converting event to mutation. Empty string disables prefixing |
eventToMutationTransformer | Function string => string | uppercase function | Determines how event name converted to mutation |
eventToActionTransformer | Function string => string | camelcase function | Determines how event name converted to action |
eventMapping | Function socket => string | Map your event from socket event data |
FYI: You can always access default plugin options if you need it (e.g. re-use default eventToActionTransformer
function):
1import VueSocketIOExt from 'vue-socket.io-extended'; 2VueSocketIOExt.defaults // -> { actionPrefix: '...', mutationPrefix: '...', ... }
For those who has migrated from old VueSocketIO to this package on existing project there is an easy way to migrate without rewriting exiting store modules.
You need to redefine 2 parameters so vue-socket.io-extended
would support the same format of actions as in vue-socket.io
.
1import VueSocketIO from 'vue-socket.io-extended'; 2import { io } from 'socket.io-client'; 3 4const ioInstance = io('https://hostname/path'); 5app.use(VueSocketIO, ioInstance, { 6 store, // vuex store instance 7 actionPrefix: 'SOCKET_', // keep prefix in uppercase 8 eventToActionTransformer: (actionName) => actionName // cancel camel case 9});
Note: Since vue-socket.io
seems to be active again the instructions might not work as described above. If you are migrating and facing some issues just create an issue with a short description of the problem. I'll try to update instructions, so you can make use of them.
This plugin follows semantic versioning.
We're using GitHub Releases.
We're more than happy to see potential contributions, so don't hesitate. If you have any suggestions, ideas or problems feel free to add new issue, but first please make sure your question does not repeat previous ones.
See the LICENSE file for license rights and limitations (MIT).
No vulnerabilities found.
No security vulnerabilities found.