native websocket with vuex integration

Overview

vue-native-websocket-es5 · Build Status npm version

Fork of https://github.com/nathantsoi/vue-native-websocket#readme but without using ES6 Proxy

native websocket implementation for Vuejs 2 and Vuex

Install

yarn add vue-native-websocket-es5

# or

npm install vue-native-websocket-es5 --save

Usage

Configuration

Automatic socket connection from an URL string

import VueNativeSock from 'vue-native-websocket-es5'
Vue.use(VueNativeSock, 'ws://localhost:9090')

Enable Vuex integration, where './store' is your local apps store:

import store from './store'
Vue.use(VueNativeSock, 'ws://localhost:9090', { store: store })

Set sub-protocol, this is optional option and default is empty string.

import VueNativeSock from 'vue-native-websocket-es5'
Vue.use(VueNativeSock, 'ws://localhost:9090', { protocol: 'my-protocol' })

Optionally enable JSON message passing:

Vue.use(VueNativeSock, 'ws://localhost:9090', { format: 'json' })

JSON message passing with a store:

import store from './store'
Vue.use(VueNativeSock, 'ws://localhost:9090', { store: store, format: 'json' })

Enable ws reconnect automatically:

Vue.use(VueNativeSock, 'ws://localhost:9090', {
  reconnection: true, // (Boolean) whether to reconnect automatically (false)
  reconnectionAttempts: 5, // (Number) number of reconnection attempts before giving up (Infinity),
  reconnectionDelay: 3000, // (Number) how long to initially wait before attempting a new (1000)
})

Manage connection manually:

Vue.use(VueNativeSock, 'ws://localhost:9090', {
  connectManually: true,
})
const vm = new Vue()
// Connect to the websocket target specified in the configuration
vm.$connect()
// Connect to an alternative websocket URL and Options e.g.
vm.$connect('ws://localhost:9090/alternative/connection/', { format: 'json' })
// do stuff with WebSockets
vm.$disconnect()

On Vuejs instance usage

var vm = new Vue({
  methods: {
    clickButton: function(val) {
      // $socket is [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) instance
      this.$socket.send('some data')
      // or with {format: 'json'} enabled
      this.$socket.sendObj({awesome: 'data'})
    }
  }
})

Dynamic socket event listeners

Create a new listener, for example:

this.$options.sockets.onmessage = (data) => console.log(data)

Remove existing listener

delete this.$options.sockets.onmessage

Vuex Store integration

Vuex integration works differently depending on if you've enabled a format

Without a format enabled

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.

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    socket: {
      isConnected: false,
      message: '',
      reconnectError: false,
    }
  },
  mutations:{
    SOCKET_ONOPEN (state, event)  {
      Vue.prototype.$socket = event.currentTarget
      state.socket.isConnected = true
    },
    SOCKET_ONCLOSE (state, event)  {
      state.socket.isConnected = false
    },
    SOCKET_ONERROR (state, event)  {
      console.error(state, event)
    },
    // default handler called for all methods
    SOCKET_ONMESSAGE (state, message)  {
      state.socket.message = message
    },
    // mutations for reconnect methods
    SOCKET_RECONNECT(state, count) {
      console.info(state, count)
    },
    SOCKET_RECONNECT_ERROR(state) {
      state.socket.reconnectError = true;
    },
  },
  actions: {
    sendMessage: function(context, message) {
      .....
      Vue.prototype.$socket.send(message)
      .....
    }
  }
})
With custom mutation names
// mutation-types.js
const SOCKET_ONOPEN = '✅ Socket connected!'
const SOCKET_ONCLOSE = '❌ Socket disconnected!'
const SOCKET_ONERROR = '❌ Socket Error!!!'
const SOCKET_ONMESSAGE = 'Websocket message received'
const SOCKET_RECONNECT = 'Websocket reconnected'
const SOCKET_RECONNECT_ERROR = 'Websocket is having issues reconnecting..'

export {
  SOCKET_ONOPEN,
  SOCKET_ONCLOSE,
  SOCKET_ONERROR,
  SOCKET_ONMESSAGE,
  SOCKET_RECONNECT,
  SOCKET_RECONNECT_ERROR
}

// store.js
import Vue from 'vue'
import Vuex from 'vuex'
import {
  SOCKET_ONOPEN,
  SOCKET_ONCLOSE,
  SOCKET_ONERROR,
  SOCKET_ONMESSAGE,
  SOCKET_RECONNECT,
  SOCKET_RECONNECT_ERROR
} from './mutation-types'

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    socket: {
      isConnected: false,
      message: '',
      reconnectError: false,
    }
  },
  mutations: {
    [SOCKET_ONOPEN](state, event)  {
      state.socket.isConnected = true
    },
    [SOCKET_ONCLOSE](state, event)  {
      state.socket.isConnected = false
    },
    [SOCKET_ONERROR](state, event)  {
      console.error(state, event)
    },
    // default handler called for all methods
    [SOCKET_ONMESSAGE](state, message)  {
      state.socket.message = message
    },
    // mutations for reconnect methods
    [SOCKET_RECONNECT](state, count) {
      console.info(state, count)
    },
    [SOCKET_RECONNECT_ERROR](state) {
      state.socket.reconnectError = true;
    }
  }
})

// index.js
import store from './store'
import {
  SOCKET_ONOPEN,
  SOCKET_ONCLOSE,
  SOCKET_ONERROR,
  SOCKET_ONMESSAGE,
  SOCKET_RECONNECT,
  SOCKET_RECONNECT_ERROR
} from './mutation-types'

const mutations = {
  SOCKET_ONOPEN,
  SOCKET_ONCLOSE,
  SOCKET_ONERROR,
  SOCKET_ONMESSAGE,
  SOCKET_RECONNECT,
  SOCKET_RECONNECT_ERROR
}

Vue.use(VueNativeSock, 'ws://localhost:9090', {
  store: store,
  mutations: mutations
})
With format: 'json' enabled

All data passed through the websocket is expected to be JSON.

Each message is JSON.parsed 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:

actions: {
    customerAdded (context) {
      console.log('action received: customerAdded')
    }
  }

Use the .sendObj({some: data}) method on the $socket object to send stringified json messages.

Custom socket event handling

Provide you own custom code to handle events received via the passToStoreHandler option. The function you provide will be passed the following arguments:

  1. event name
  2. event
  3. original/default handler code function 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:

Vue.use(VueNativeSock, 'ws://localhost:9090', {
  passToStoreHandler: function (eventName, event) {
    if (!eventName.startsWith('SOCKET_')) { return }
    let method = 'commit'
    let target = eventName.toUpperCase()
    let msg = event
    if (this.format === 'json' && event.data) {
      msg = JSON.parse(event.data)
      if (msg.mutation) {
        target = [msg.namespace || '', msg.mutation].filter((e) => !!e).join('/')
      } else if (msg.action) {
        method = 'dispatch'
        target = [msg.namespace || '', msg.action].filter((e) => !!e).join('/')
      }
    }
    this.store[method](target, msg)
  }
})

Here is an example of do some preprocessing, then pass the event onto the original handler code:

Vue.use(VueNativeSock, 'ws://localhost:9090', {
  passToStoreHandler: function (eventName, event, next) {
    event.data = event.should_have_been_named_data
    next(eventName, event)
  }
})

Examples

TODO: post your example here!

Credits

Derived from https://github.com/MetinSeylan/Vue-Socket.io

You might also like...
Hybrid mobile template built with Ionic Vue using capacitor for native builds
Hybrid mobile template built with Ionic Vue using capacitor for native builds

Ionic Vue Mobile Template 04 Hybrid mobile template built with Ionic Vue using capacitor for native builds. Template is inspired by the new Capitec Ba

🖼 Tiny vue wrapper for supporting native picture-in-picture mode.

V-Pip 🖼 Features Vue 💚 Picture-in-picture! Built using TypeScript Versions For Vue 3.x version – npm i v-pip@2 For Vue 2.x version – npm i v-pip@1 T

Assets portfolio available on native web, iOS, Android

Crypto exchange app Assets portfolio available on native web, iOS, Android http://cryptoexchanger.netlify.app/ Features Simulations of buying, selling

PrestaShop integration with Vue Storefront created by Binshops.
PrestaShop integration with Vue Storefront created by Binshops.

Vue Storefront 2 eCommerce integration with PrestaShop This repository is a PrestaShop integration for Vue Storefront 2. Beta version. Installation in

Solana-wallets-vue - Solana wallet integration for Vue 2 and 3
Solana-wallets-vue - Solana wallet integration for Vue 2 and 3

Solana Wallets Vue Integrates Solana wallets in your Vue 2 and Vue 3 application

Hermes CI is an open-source continuous integration platform
Hermes CI is an open-source continuous integration platform

Hermes CI Hermes CI is an open-source continuous integration platform mainly written in Go. Name Hermes is the winged herald and messenger of the Olym

 Vue Storefront 2 integration with PrestaShop
Vue Storefront 2 integration with PrestaShop

Convert your traditional PrestaShop website into a fast, mobile friendly and modern website.

A basic setup for Vue.js project . vuex, vuex-persistedstate, vue-router , vue-resource , sweetalert2.

Project setup npm install Compiles and hot-reloads for development npm run serve Compiles and minifies for production npm run build Lints and fixes

mmf-blog vue2.0 (vue2, vue-router, vuex)

mmf-blog vuejs 2.0 v2 中文说明 demo: http://vue2.mmxiaowu.com The main technical stack: vue2, vue2-router, vuex, webpack, babel, eslint Other versions rea

Owner
null
TMM is a Linux native game modding tool. it allows to install and depoly mods for Linux native and wine games.

TMM is a Linux native mod manager made with the Tauri toolkit, it can, install, load, remove, and deploy mods for both linux native and wine games.

Mathiew May 119 Jan 2, 2023
Payment-integration - A simple payment integration with m-pesa payment gateway built with express

mpesav2 Build Setup # install dependencies $ npm install # serve with hot reload at localhost:3000 $ npm run dev # build for production and launch s

Kihika Samuel 0 Jan 3, 2022
🚀 Lanyard API plugin for Vue to easily track your Discord status. Supports REST and WebSocket methods.

?? Lanyard API plugin for Vue to easily track your Discord status. Supports REST and WebSocket methods.

EGGSY 30 Sep 3, 2022
A websocket based remote event system

vue-remote A websocket based remote event system for Vue.js. Works with Vue 2.0, untested with Vue 1.0. Installation 1.) Install package via NPM npm i

Justin MacArthur 22 Oct 22, 2022
Native mobile applications using Vue and NativeScript.

Supporting NativeScript-Vue NativeScript-Vue is an MIT-licensed open source project made possible by our sponsors: and these awesome backers: Tiago Al

NativeScript-Vue 5k Jan 9, 2023
A HashiCorp Vault UI written with VueJS and Vault native Go API

Goldfish Vault UI - Live Demo Share this repo with your colleagues! What is this? Goldfish - A HashiCorp Vault UI and workflow tool. pic.twitter.com/u

Tony Cai 2.2k Dec 18, 2022
Laqu-l 130 Dec 27, 2022
Native desktop applications using Vue.js.

Vuido Create native desktop applications for Windows, OS X and Linux using Vue.js. Introduction Vuido is a framework for creating native desktop appli

Michał Męciński 6.1k Jan 5, 2023
A Vue component to use native sharing mechanism of the device as part of the Web Share API.

vue-navigator-share A Vue component to use native sharing mechanism of the device as part of the Web Share API. Support only https and mobile browser

Gabriel Bibiano 20 Nov 27, 2022
Cloud-native platform for building an NFT Marketplace on top of Algorand blockchain.

Built on OpenAlgoNFT OpenAlgoNFT is an open-source cloud-native platform for building an NFT Marketplace on top of Algorand blockchain. Learn more on

Ulam Labs 111 Dec 7, 2022