Giter Site home page Giter Site logo

vue-native-websocket's Introduction

vue-native-websocket

native websocket implementation for Vuejs 2 and Vuex

Install

yarn add vue-native-websocket

# or

npm install vue-native-websocket --save

Usage

Configuration

Automatic socket connection from an URL string

import VueNativeSock from 'vue-native-websocket'
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'
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' })

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.

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

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    socket: {
      isConnected: false,
      message: '',
    }
  },
  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.message = message
    }
  }
})
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.

Examples

TODO: post your example here!

Credits

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

vue-native-websocket's People

Contributors

codeofsumit avatar jeystaats avatar metinseylan avatar michgeek avatar nathantsoi avatar panicisreal avatar pieterjandesmedt avatar whitekkk avatar

Watchers

 avatar  avatar  avatar

Forkers

antuotuto

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.