Tutorial

Integrating Vue.js and Socket.io

Published on March 28, 2017
author

Joshua Bemenderfer

Integrating Vue.js and Socket.io

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Websockets are a powerful way to enable bidirectional communication between the client and the server, and socket.io is one of the leading libraries that simplifies connection handling with websockets and alternative transports. Let’s combine it with Vue in order to be able to use socket.io directly in our components!

Installation

First let’s install socket.io-client and vue-socket.io using Yarn or NPM.

# Yarn
$ yarn add socket.io-client vue-socket.io
# NPM
$ npm install socket.io-client vue-socket.io --save

Usage

For the purposes of this guide, we’re going to assume you already have a server running with socket.io locally on, let’s say, port 4113.

First, enable the vue-socket.io plugin in your app startup file:

main.js
import Vue from 'vue';
import socketio from 'socket.io';
import VueSocketIO from 'vue-socket.io';

export const SocketInstance = socketio('http://localhost:4113');

Vue.use(VueSocketIO, SocketInstance)

// The usual app stuff goes here.
...

Now, we can bind to socket events directly in our components:

IListenToSockets.vue
<template>
  <div>
    <p v-if="isConnected">We're connected to the server!</p>
    <p>Message from server: "{{socketMessage}}"</p>
    <button @click="pingServer()">Ping Server</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isConnected: false,
      socketMessage: ''
    }
  },

  sockets: {
    connect() {
      // Fired when the socket connects.
      this.isConnected = true;
    },

    disconnect() {
      this.isConnected = false;
    },

    // Fired when the server sends something on the "messageChannel" channel.
    messageChannel(data) {
      this.socketMessage = data
    }
  },

  methods: {
    pingServer() {
      // Send the "pingServer" event to the server.
      this.$socket.emit('pingServer', 'PING!')
    }
  }
}
</script>

Vuex integration

If you’re using Vuex, you can have store mutations fired when socket channels receive messages, just by adding your Vuex store to the plugin initialization in main.js.

main.js
...
import { MyVuexStore } from './my-vuex-store.js'

Vue.use(VueSocketIO, SocketInstance, MyVuexStore)
...

All mutations triggered by sockets are prefixed by SOCKET_

So, for example, if your channel is called messageChannel, the corresponding Vuex mutation would be SOCKET_MESSAGECHANNEL. In your store configuration, that would look like this:

my-vuex-store.js

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

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    isConnected: false,
    socketMessage: ''
  },

  mutations:{
    SOCKET_CONNECT(state) {
      state.isConnected = true;
    },

    SOCKET_DISCONNECT(state) {
      state.isConnected = false;
    },

    SOCKET_MESSAGECHANNEL(state, message) {
      state.socketMessage = message
    }
  }
})

Not bad eh?

For more detailed information, take a look at the vue-socket.io and socket.io documentation.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products


About the authors
Default avatar
Joshua Bemenderfer

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
1 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

very hard to follow. What does “the usual stuff” mean? Like, if I am on this page is because I need help and want to learn. The author is not writing for folks who don’t know but for folks who know as much as the author. Like, this is confusing/

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel