Gathering detailed insights and metrics for native-websocket-vue3
Gathering detailed insights and metrics for native-websocket-vue3
Native websocket implementation for Vuejs3 Vuex, and Pinia.
npm install native-websocket-vue3
Typescript
Module System
Node Version
NPM Version
JavaScript (100%)
Verify real, reachable, and deliverable emails with instant MX records, SMTP checks, and disposable email detection.
Total Downloads
2,844
Last Day
1
Last Week
18
Last Month
78
Last Year
1,504
MIT License
2 Stars
2 Commits
1 Watchers
1 Branches
1 Contributors
Updated on Jan 26, 2025
Minified
Minified + Gzipped
Latest Version
3.0.15
Package Id
native-websocket-vue3@3.0.15
Unpacked Size
42.79 kB
Size
12.46 kB
File Count
11
NPM Version
8.19.3
Node Version
18.13.0
Published on
Mar 03, 2023
Cumulative downloads
Total Downloads
Last Day
-85.7%
1
Compared to previous day
Last Week
63.6%
18
Compared to previous week
Last Month
44.4%
78
Compared to previous month
Last Year
18.6%
1,504
Compared to previous year
native websocket implementation for Vuejs3 Vuex, and Pinia.
1yarn add native-websocket-vue3 2 3# or 4 5npm install native-websocket-vue3 --save
Automatic socket connection from an URL string
1import VueNativeSock from 'native-websocket-vue3' 2app.use(VueNativeSock, 'ws://localhost:9090')
Enable Vuex integration, where './store'
is your local apps store:
1import store from './store' 2app.use(VueNativeSock, 'ws://localhost:9090', { store: store })
Set sub-protocol, this is optional option and default is empty string.
1import VueNativeSock from 'native-websocket-vue3' 2app.use(VueNativeSock, 'ws://localhost:9090', { protocol: 'my-protocol' })
Optionally enable JSON message passing:
1app.use(VueNativeSock, 'ws://localhost:9090', { format: 'json' })
JSON message passing with a store:
1import store from './store' 2app.use(VueNativeSock, 'ws://localhost:9090', { store: store, format: 'json' })
Enable ws reconnect automatically:
1app.use(VueNativeSock, 'ws://localhost:9090', { 2 reconnection: true, // (Boolean) whether to reconnect automatically (false) 3 reconnectionAttempts: 5, // (Number) number of reconnection attempts before giving up (Infinity), 4 reconnectionDelay: 3000, // (Number) how long to initially wait before attempting a new (1000) 5})
Manage connection manually:
1app.use(VueNativeSock, 'ws://localhost:9090', {
2 connectManually: true,
3})
4const vm = new Vue()
5// Connect to the websocket target specified in the configuration
6vm.$connect()
7// Connect to an alternative websocket URL and Options e.g.
8vm.$connect('ws://localhost:9090/alternative/connection/', { format: 'json' })
9// do stuff with WebSockets
10vm.$disconnect()
1var vm = new Vue({ 2 methods: { 3 clickButton: function(val) { 4 // $socket is [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) instance 5 this.$socket.send('some data') 6 // or with {format: 'json'} enabled 7 this.$socket.sendObj({awesome: 'data'}) 8 } 9 } 10})
Create a new listener, for example:
1this.$options.sockets.onmessage = (data) => console.log(data)
Remove existing listener
1delete this.$options.sockets.onmessage
Vuex integration works differently depending on if you've enabled a format
Socket events will commit mutations on the root store corresponding to the following events
SOCKET_ONOPEN
SOCKET_ONCLOSE
SOCKET_ONERROR
SOCKET_ONMESSAGE
Each callback is passed the raw websocket event object
Update state in the open, close and error callbacks. You can also check the socket state directly with the this.$socket
object on the main Vue object.
Handle all the data in the SOCKET_ONMESSAGE
mutation.
Reconect events will commit mutations SOCKET_RECONNECT
and SOCKET_RECONNECT_ERROR
.
1 2app.use(Vuex); 3 4export default new Vuex.Store({ 5 state: { 6 socket: { 7 isConnected: false, 8 message: '', 9 reconnectError: false, 10 } 11 }, 12 mutations:{ 13 SOCKET_ONOPEN (state, event) { 14 Vue.prototype.$socket = event.currentTarget 15 state.socket.isConnected = true 16 }, 17 SOCKET_ONCLOSE (state, event) { 18 state.socket.isConnected = false 19 }, 20 SOCKET_ONERROR (state, event) { 21 console.error(state, event) 22 }, 23 // default handler called for all methods 24 SOCKET_ONMESSAGE (state, message) { 25 state.socket.message = message 26 }, 27 // mutations for reconnect methods 28 SOCKET_RECONNECT(state, count) { 29 console.info(state, count) 30 }, 31 SOCKET_RECONNECT_ERROR(state) { 32 state.socket.reconnectError = true; 33 }, 34 }, 35 actions: { 36 sendMessage: function(context, message) { 37 ..... 38 this.$socket.sendObj(message) 39 ..... 40 } 41 } 42})
1// mutation-types.js 2const SOCKET_ONOPEN = '✅ Socket connected!' 3const SOCKET_ONCLOSE = '❌ Socket disconnected!' 4const SOCKET_ONERROR = '❌ Socket Error!!!' 5const SOCKET_ONMESSAGE = 'Websocket message received' 6const SOCKET_RECONNECT = 'Websocket reconnected' 7const SOCKET_RECONNECT_ERROR = 'Websocket is having issues reconnecting..' 8 9export { 10 SOCKET_ONOPEN, 11 SOCKET_ONCLOSE, 12 SOCKET_ONERROR, 13 SOCKET_ONMESSAGE, 14 SOCKET_RECONNECT, 15 SOCKET_RECONNECT_ERROR 16} 17 18// store.js 19import Vue from 'vue' 20import Vuex from 'vuex' 21import { 22 SOCKET_ONOPEN, 23 SOCKET_ONCLOSE, 24 SOCKET_ONERROR, 25 SOCKET_ONMESSAGE, 26 SOCKET_RECONNECT, 27 SOCKET_RECONNECT_ERROR 28} from './mutation-types' 29 30Vue.use(Vuex); 31 32export default new Vuex.Store({ 33 state: { 34 socket: { 35 isConnected: false, 36 message: '', 37 reconnectError: false, 38 } 39 }, 40 mutations: { 41 [SOCKET_ONOPEN](state, event) { 42 state.socket.isConnected = true 43 }, 44 [SOCKET_ONCLOSE](state, event) { 45 state.socket.isConnected = false 46 }, 47 [SOCKET_ONERROR](state, event) { 48 console.error(state, event) 49 }, 50 // default handler called for all methods 51 [SOCKET_ONMESSAGE](state, message) { 52 state.socket.message = message 53 }, 54 // mutations for reconnect methods 55 [SOCKET_RECONNECT](state, count) { 56 console.info(state, count) 57 }, 58 [SOCKET_RECONNECT_ERROR](state) { 59 state.socket.reconnectError = true; 60 } 61 } 62}) 63 64// index.js 65import store from './store' 66import { 67 SOCKET_ONOPEN, 68 SOCKET_ONCLOSE, 69 SOCKET_ONERROR, 70 SOCKET_ONMESSAGE, 71 SOCKET_RECONNECT, 72 SOCKET_RECONNECT_ERROR 73} from './mutation-types' 74 75const mutations = { 76 SOCKET_ONOPEN, 77 SOCKET_ONCLOSE, 78 SOCKET_ONERROR, 79 SOCKET_ONMESSAGE, 80 SOCKET_RECONNECT, 81 SOCKET_RECONNECT_ERROR 82} 83 84app.use(VueNativeSock, 'ws://localhost:9090', { 85 store: store, 86 mutations: mutations 87})
format: 'json'
enabledAll data passed through the websocket is expected to be JSON.
Each message is JSON.parse
d if there is a data (content) response.
If there is no data, the fallback SOCKET_ON*
mutation is called with the original event data, as above.
If there is a .namespace
on the data, the message is sent to this namespaced: true
store (be sure to turn this on in the store module).
If there is a .mutation
value in the response data, the corresponding mutation is called with the name SOCKET_[mutation value]
If there is an .action
value in the response data ie. action: 'customerAdded'
, the corresponding action is called by name:
1actions: { 2 customerAdded (context) { 3 console.log('action received: customerAdded') 4 } 5 }
Use the .sendObj({some: data})
method on the $socket
object to send stringified json messages.
Provide you own custom code to handle events received via the passToStoreHandler
option. The function you provide will be passed the following arguments:
function (eventName, event)
. This allows you to optionally do some basic preprocessing before handing the event over to the original handler.The original passToStore code is used if no passToStoreHandler
is configured.
Here is an example of passing in a custom handler. This has the original passToStore code to give you an example of what you can do:
1app.use(VueNativeSock, 'ws://localhost:9090', { 2 passToStoreHandler: function (eventName, event) { 3 if (!eventName.startsWith('SOCKET_')) { return } 4 let method = 'commit' 5 let target = eventName.toUpperCase() 6 let msg = event 7 if (this.format === 'json' && event.data) { 8 msg = JSON.parse(event.data) 9 if (msg.mutation) { 10 target = [msg.namespace || '', msg.mutation].filter((e) => !!e).join('/') 11 } else if (msg.action) { 12 method = 'dispatch' 13 target = [msg.namespace || '', msg.action].filter((e) => !!e).join('/') 14 } 15 } 16 this.store[method](target, msg) 17 } 18})
Here is an example of do some preprocessing, then pass the event onto the original handler code:
1app.use(VueNativeSock, 'ws://localhost:9090', { 2 passToStoreHandler: function (eventName, event, next) { 3 event.data = event.should_have_been_named_data 4 next(eventName, event) 5 } 6})
TODO: NuxtJs, Quasar Examples.
Vue2 use the original version native-websocket-vue3
No vulnerabilities found.
No security vulnerabilities found.