Websocket Plugin That Supports Vue3 and Vuex

Websocket Plugin That Supports Vue3 and Vuex

Websocket plugin that supports vue 3 and vuex | Websocket plugin that supports vue 3 and vuex

vue-native-websocket-vue3 · 

Websocket plugin that supports vue 3 and vuex | Websocket plugin that supports vue 3 and vuex

English documents please move: README-EN.md

Plug-in installation

yarn add vue-native-websocket-vue3

## or

npm install vue-native-websocket-vue3 --save

Plug-in use

If your project has TypeScript enabled main.ts, import and use the plug- in in the file.

main.jsImport and use it if it is not enabled .

When using the plug-in, the second parameter is required and is your websocketserver connection address.

import  VueNativeSock  from  "vue-native-websocket-vue3" ;

// Use the VueNativeSock plugin and configure the 
app . Use ( VueNativeSock , "" ) ;

Plug-in configuration items

The plug-in provides some configuration options, which improves the flexibility of the plug-in and can better adapt to the business needs of developers.

Enable Vuex integration

In main.ts | main.jsthe introduction vuex, when using the plug, the third parameter is that users can transmit configuration item, he is an object type, added in an object storeattribute, the value of the introduced vuex.

import  store  from  "./store" ;

app . use ( VueNativeSock , "" , { 
    store : store 
} ) ;

If vuex integration is enabled, state and mutations methods need to be defined in its configuration file. The methods defined in mutations are 6 monitors of websocket, and you can do corresponding operations in these monitors.

import  {  createStore  }  from  "vuex" ; 
import  main  from  "../main" ;

export  default  createStore ( { 
  state : { 
    socket : { 
      // Connection status 
      isConnected : false , 
      // Message content 
      message : "" , 
      // Reconnect error 
      reconnectError : false , 
      // Heartbeat message sending time 
      heartBeatInterval : 50000 , 
      // Heartbeat Timer 
      heartBeatTimer : 0 
    } 
  } , 
  mutations : { 
    // connection open 
    SOCKET_ONOPEN ( state ,  event ) { 
      main . config . globalProperties . $socket  =  event . currentTarget ; 
      state . socket . isConnected  =  true ; 
      // When the connection is successful, start timing to send heartbeat messages to avoid being disconnected by the server 
      state . socket . heartBeatTimer  =  setInterval ( ( )  = >  { 
        const  message  =  "heartbeat message" ; 
        state . socket . isConnected  && 
          main . config .globalProperties . $socket . sendObj ( { 
            code : 200 , 
            msg : message 
          } ) ; 
      } ,  state . socket . heartBeatInterval ) ; 
    } , 
    // Connection closed 
    SOCKET_ONCLOSE ( state ,  event )  { 
      state . socket . isConnected  =  false ; 
      // Stop the heartbeat message when the connection is closed 
      clearInterval ( state . Socket. HeartBeatTimer ) ; 
      State . Socket . HeartBeatTimer  =  0 ; 
      Console . Log ( "disconnected:"  +  new new  a Date ( ) ) ; 
      Console . Log ( Event ) ; 
    } , 
    // error 
    SOCKET_ONERROR ( State ,  Event )  { 
      console . error ( state ,  event ) ; 
    } ,
    // receive a message sent by the server 
    SOCKET_ONMESSAGE ( State ,  Message )  { 
      State . Socket . Message  =  Message ; 
    } , 
    // automatically reconnect 
    SOCKET_RECONNECT ( State ,  COUNT )  { 
      Console . Info ( "reconnection of the message system .. ." ,  state ,  count ) ; 
    } , 
    //reconnect error 
    SOCKET_RECONNECT_ERROR ( state )  { 
      state . socket .reconnectError  =  true ; 
    } 
  } , 
  modules : { } 
} ) ;
Custom method name

You can also mutationscustomize the default listener event name of websocket.

// mutation-types.ts 
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.ts 
import  {  createStore  }  from  "vuex" ; 
import  main  from  "../main" ; 
import  { 
  SOCKET_ONOPEN , 
  SOCKET_ONCLOSE , 
  SOCKET_ONERROR , 
  SOCKET_ONMESSAGE , 
  SOCKET_RECONNECT , 
  SOCKET_RECONNECT_ERROR 
}  from  "./mutation-types"

export  default  createStore ( { 
  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 ; 
    } 
  } , 
  modules : { } 
} ) ;

// 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 
}

app . use ( VueNativeSock , "" , { 
  store : store , 
  mutations : mutations 
} ) ;
Other configuration

The following methods are all passable parameters of the plug-in and can be storeused with

  • Set the websocket sub-protocol default, consider it as an empty string.
{
     " protocol " : " my-protocol " 
}
  • Enable JSON messaging. After enabling, data sending and receiving will use json as the data format.
{ 
     " format " : " json " 
}
  • Automatic reconnection is reconnectionenabled, the number reconnectionAttemptsof reconnections and the reconnection interval can be configured when enabledreconnectionDelay
{
   " reconnection " : true ,
   " reconnectionAttempts " : 5 , 
   " reconnectionDelay " : 3000 
}
  • Manually manage connections
{
   " connectManually " : true 
}

After enabling manual connection management, the connection will not be automatically connected when the project starts. You can call the connection method on a specific component of the project to connect. Call the close method when the component is destroyed to close the connection.

If you enable manual connection, you must enable vuex, otherwise this setting will not take effect.

  // Connect to the websocket server, the parameter is the websocket service address 
  this . $connect ( "" ) ; 
  // Close the connection 
  this . $disconnect ( ) ;
  • When custom socket event processing triggers the mutations event in vuex, you can choose to write your own function processing and do what you want to do. You can pass in passToStoreHandlerparameters when using the plug-in . If you don’t pass it, use the default processing function. The definition of the function is as follows:
export  default  class  { 
    /** 
     * Default event handling function 
     * @param eventName event name 
     * @param event event 
     */ 
    defaultPassToStore ( 
        eventName : string , 
        event : { 
            data : string ; 
            mutation : string ; 
            namespace : string ; 
            action : string ; 
        } 
    ) : void  { 
        // If the beginning of the event name is not SOCKET_ then terminate the function 
        if  ( !eventName . startsWith ( "SOCKET_" ) )  { 
            return ; 
        } 
        let  method  =  "commit" ; 
        // The letter of the event name is converted to uppercase 
        let  target  =  eventName . toUpperCase ( ) ; 
        // message content 
        let  msg  =  event ; 
        // data exists and The data is in json format 
        if  ( this . Format  ===  "json"  &&  event . Data )  { 
            // convert data from json string to json object 
            msg  = JSON . Parse ( event . Data ) ; 
            // Determine whether msg is synchronous or asynchronous 
            if  ( msg . Mutation )  { 
                target  =  [ msg . Namespace  ||  "" ,  msg . Mutation ] . Filter ( ( e : string )  => ! ! e ) . join ( "/" ) ; 
            }  else  if  ( msg .action )  { 
                method  =  "dispatch" ; 
                target  =  [ msg . namespace  ||  "" ,  msg . action ] . filter ( ( e : string )  => !! e ) . join ( "/" ) ; 
            } 
        } 
        if  ( this . mutations )  { 
            target  =  this . mutations [ target]  ||  target ; 
        } 
        // trigger the method in storm 
        this . store [ method ] ( target ,  msg ) ; 
    } 
}

When you want to customize a function, this function receives 3 parameters:

  • event name
  • event
  • Default event handling, which gives you the option to perform some basic preprocessing before handing over the event to the original handler

Below is an example

app . use ( VueNativeSock ,  "" ,  { 
  passToStoreHandler : function  ( eventName ,  event ,  next )  { 
      event . data  =  event . should_have_been_named_data 
      next ( eventName ,  event ) 
  } 
} )

Use in components

After finishing the above configuration, it can be used in the component. The following shows an example of sending data.

export  default  defineComponent ( { 
  methods : { 
    clickButton : function ( val )  { 
        // call the send method to send data in string form 
        this . $socket . send ( 'some data' ) ; 
        // if fomat is configured as json, you can Call the sendObj method to send data 
        this . $socket . SendObj ( {  awesome : 'data' }  ) ; 
    } 
  } 
} )

Message monitoring means receiving messages pushed by the websocket server. The sample code for message monitoring is shown below.

// optionsAPI usage 
this . $options . sockets . onmessage  =  ( res : {  data : string  } )  =>  { 
  console . log ( data ) ; 
}

// CompositionAPI Usage 
Import  {  getCurrentInstance  }  from  "VUE" ; 
const  the currentInstance of the  =  getCurrentInstance ( ) ; 
( the currentInstance of the ? . AppContext . Config . GlobalProperties . Sockets ) . OnMessage  =  ( RES : { 
  Data : String ; 
} )  =>  { 
  Console . log ( data ) ;
}

Remove message monitoring

delete  this . $options . sockets . onmessage

Write at the end

So far, all the methods of using the plug-in have been introduced.

If you want to know more about the plug-in source code, please move to the project's GitHub repository: vue-native-websocket-vue3

Original plug-in code address: vue-native-websocket

Download Details:

Author: likaia

Source Code: https://github.com/likaia/vue-native-websocket-vue3

vue vuejs javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

8 Popular Websites That Use The Vue.JS Framework

In this article, we are going to list out the most popular websites using Vue JS as their frontend framework. Vue JS is one of those elite progressive JavaScript frameworks that has huge demand in the web development industry. Many popular websites are developed using Vue in their frontend development because of its imperative features.

Vue Native is a framework to build cross platform native mobile apps using JavaScript

Vue Native is a framework to build cross platform native mobile apps using JavaScript. It is a wrapper around the APIs of React Native. So, with Vue Native, you can do everything that you can do with React Native. With Vue Native, you get

How to Make a Simple Vue Custom Select Component

In this article, you’ll learn how to build a Vue custom select component that can be easily be styled using your own CSS. In fact, it’s the same component that we use in production on Qvault, and you can see it in action on the playground.

Creating a Custom Tooltip Component in Vue

There are plenty of libraries out there that will have you up and running with a good tooltip solution in minutes. However, if you are like me, you are sick and tired of giant dependency trees that have the distinct possibility of breaking at any time.

Vue ShortKey plugin for Vue.js

Vue-ShortKey - The ultimate shortcut plugin to improve the UX .Vue-ShortKey - plugin for VueJS 2.x accepts shortcuts globaly and in a single listener.