All Projects → mclintprojects → Actioncable Vue

mclintprojects / Actioncable Vue

Licence: mit
A Vue plugin that makes integrating Rails Action Cable dead-easy.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Actioncable Vue

Engine.io Client
Stars: ✭ 649 (+370.29%)
Mutual labels:  websocket, real-time
Gophergameserver
🏆 Feature packed, easy-to-use game server API for Go back-ends and Javascript clients. Tutorials and examples included!
Stars: ✭ 61 (-55.8%)
Mutual labels:  websocket, real-time
Agoo
A High Performance HTTP Server for Ruby
Stars: ✭ 679 (+392.03%)
Mutual labels:  rails, websocket
Engine.io
socket.io
Stars: ✭ 4,329 (+3036.96%)
Mutual labels:  websocket, real-time
Autobahn Java
WebSocket & WAMP in Java for Android and Java 8
Stars: ✭ 1,467 (+963.04%)
Mutual labels:  websocket, real-time
Primus
⚡ Primus, the creator god of the transformers & an abstraction layer for real-time to prevent module lock-in.
Stars: ✭ 4,302 (+3017.39%)
Mutual labels:  websocket, real-time
Rtb
Benchmarking tool to stress real-time protocols
Stars: ✭ 35 (-74.64%)
Mutual labels:  websocket, real-time
Ws
Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js
Stars: ✭ 17,419 (+12522.46%)
Mutual labels:  websocket, real-time
Sandstone
PHP microframework designed to build a RestApi working together with a websocket server. Build a real time RestApi!
Stars: ✭ 98 (-28.99%)
Mutual labels:  websocket, real-time
Autobahn Js
WAMP in JavaScript for Browsers and NodeJS
Stars: ✭ 1,345 (+874.64%)
Mutual labels:  websocket, real-time
Centrifuge
Real-time messaging library for Go with scalability in mind
Stars: ✭ 446 (+223.19%)
Mutual labels:  websocket, real-time
Action Cable Signaling Server
🤝Rails implementation of a WebRTC Signaling Server
Stars: ✭ 118 (-14.49%)
Mutual labels:  rails, websocket
Wampsharp
A C# implementation of WAMP (The Web Application Messaging Protocol)
Stars: ✭ 355 (+157.25%)
Mutual labels:  websocket, real-time
Centrifugo
Scalable real-time messaging server in a language-agnostic way. Set up once and forever.
Stars: ✭ 5,649 (+3993.48%)
Mutual labels:  websocket, real-time
Vue Project
基于vue-cli构建的财务后台管理系统(vue2+vuex+axios+vue-router+element-ui+echarts+websocket+vue-i18n)
Stars: ✭ 301 (+118.12%)
Mutual labels:  websocket, vuejs2
Sockjs Client
WebSocket emulation - Javascript client
Stars: ✭ 7,808 (+5557.97%)
Mutual labels:  websocket, real-time
Autobahn Python
WebSocket and WAMP in Python for Twisted and asyncio
Stars: ✭ 2,305 (+1570.29%)
Mutual labels:  websocket, real-time
Thunderpush
Push messages to browsers in real-time ⚡️
Stars: ✭ 202 (+46.38%)
Mutual labels:  websocket, real-time
Sec Api
sec.gov EDGAR API | search & filter SEC filings | over 150 form types supported | 10-Q, 10-K, 8, 4, 13, S-11, ... | insider trading
Stars: ✭ 71 (-48.55%)
Mutual labels:  websocket, real-time
Iot Technical Guide
🐝 IoT Technical Guide --- 从零搭建高性能物联网平台及物联网解决方案和Thingsboard源码分析 ✨ ✨ ✨ (IoT Platform, SaaS, MQTT, CoAP, HTTP, Modbus, OPC, WebSocket, 物模型,Protobuf, PostgreSQL, MongoDB, Spring Security, OAuth2, RuleEngine, Kafka, Docker)
Stars: ✭ 2,334 (+1591.3%)
Mutual labels:  websocket, real-time

Last Commit All Contributors Count Bundle Size Downloads

ActionCableVue is an easy-to-use Action Cable integration for VueJS.

🚀 Installation

npm install actioncable-vue --save
// Vue 2.x
import Vue from 'vue';
import ActionCableVue from 'actioncable-vue';
import App from './App.vue';

Vue.use(ActionCableVue, {
  debug: true,
  debugLevel: 'error',
  connectionUrl: 'ws://localhost:5000/api/cable', // or function which returns a string with your JWT appended to your server URL as a query parameter
  connectImmediately: true,
});

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app');
// Vue 3.x
import { createApp } from 'vue';
import App from './App.vue';
import ActionCableVue from 'actioncable-vue';

const actionCableVueOptions = {
  debug: true,
  debugLevel: 'error',
  connectionUrl: 'ws://localhost:5000/api/cable',
  connectImmediately: true
};

createApp(App)
  .use(store)
  .use(router)
  .use(ActionCableVue, actionCableVueOptions)
  .mount('#app');
Parameters Type Default Required Description
debug Boolean false Optional Enable logging for debug
debugLevel String error Optional Debug level required for logging. Either info, error, or all
connectionUrl String/Function null Optional ActionCable websocket server url. Omit it for the default behavior
connectImmediately Boolean true Optional ActionCable connects to your server immediately. If false, ActionCable connects on the first subscription.
store Object null Optional Vuex store

Table of content

Wall of Appreciation

  • Many thanks to @x88BitRain for adding Vue 3 compatibility

☕ Support ActionCable-Vue

If you'd like to donate to support the continued development and maintenance of actioncable-vue, you can do so here.

🌈 Component Level Usage

If you want to listen to channel events from your Vue component, you need to either add a channels object in the Vue component, or if you're using vue-class-component define a channels property. Each defined object in channels will start to receive events provided you subscribe correctly.

new Vue({
  data() {
    return {
      message: 'Hello world'
    };
  },
  channels: {
    ChatChannel: {
      connected() {},
      rejected() {},
      received(data) {},
      disconnected() {}
    }
  },
  methods: {
    sendMessage: function() {
      this.$cable.perform({
        channel: 'ChatChannel',
        action: 'send_message',
        data: {
          content: this.message
        }
      });
    }
  },
  mounted() {
    this.$cable.subscribe({
      channel: 'ChatChannel',
      room: 'public'
    });
  }
});

Alternative definition for vue-class-component users.

@Component
export default class ChatComponent extends Vue {
  @Prop({required: true}) private id!: string;

  get channels() {
    return {
      ChatChannel: {
        connected() {
          console.log('connected');
        },
        rejected() {},
        received(data) {},
        disconnected() {}
      }
    };
  }

  sendMessage(){
    this.$cable.perform({
      channel: 'ChatChannel',
      action: 'send_message',
      data: {
        content: this.message
      }
    });
  }

  async mounted() {
    this.$cable.subscribe({
      channel: 'ChatChannel',
      room: 'public'
    });
  }
}

✨ Subscriptions

1. Subscribing to a channel

Define a channels object in your component matching the action cable server channel name you passed for the subscription.

new Vue({
  channels: {
    ChatChannel: {
      connected() {
        console.log('I am connected.');
      }
    }
  },
  mounted() {
    this.$cable.subscribe({
      channel: 'ChatChannel'
    });
  }
});
Important

ActionCableVue automatically uses your ActionCable server channel name if you do not pass in a specific channel name to use in your channels. It will also override clashing channel names.

2. Subscribing to the same channel but different rooms
new Vue({
  channels: {
    chat_channel_public: {
      connected() {
        console.log('I am connected to the public chat channel.');
      }
    },
    chat_channel_private: {
      connected() {
        console.log('I am connected to the private chat channel.');
      }
    }
  },
  mounted() {
    this.$cable.subscribe({
        channel: 'ChatChannel',
        room: 'public'
      },
      'chat_channel_public'
    );
    this.$cable.subscribe({
        channel: 'ChatChannel',
        room: 'private'
      },
      'chat_channel_private'
    );
  }
});
3. Subscribing to a channel with a computed name
// Conversations.vue

new Vue({
  methods: {
    openConversation(conversationId){
      this.$router.push({name: 'conversation', params: {id: conversationId});
    }
  }
});
// Chat.vue

new Vue({
  channels: {
    computed: [{
      channelName() {
        return `${this.$route.params.conversationId}`;
      },
      connected() {
        console.log('I am connected to a channel with a computed name.');
      },
      rejected() {},
      received(data) {},
      disconnected() {}
    }]
  },
  mounted() {
    this.$cable.subscribe({
      channel: this.$route.params.conversationId
    });
  }
});

🎃 Unsubscriptions

When your component is destroyed ActionCableVue automatically unsubscribes from any channel that component was subscribed to.

new Vue({
  methods: {
    unsubscribe() {
      this.$cable.unsubscribe('ChatChannel');
    }
  },
  mounted() {
    this.$cable.subscribe({
      channel: 'ChatChannel'
    });
  }
});

👺 Manually connect to the server

ActionCableVue automatically connects to your Action Cable server if connectImmediately is not set to false during setup. If you do set connectImmediately to false you can manually trigger a connection to your ActionCable server with this.$cable.connection.connect.

new Vue({
  methods: {
    connectWithRefreshedToken(token) {
      // You can optionally pass in a connection URL string
      // You can optionally pass in a function that returns a connection URL
      // You can choose not to pass in anything and it'll reconnect with the connection URL provided during setup.
      this.$cable.connection.connect(`ws://localhost:5000/api/cable?token=${token}`);
    }
  }
});

👽 Disconnecting from the server

new Vue({
  methods: {
    disconnect() {
      this.$cable.connection.disconnect();
    }
  }
});

💎 Performing an action on your Action Cable server

Requires that you have a method defined in your Rails Action Cable channel whose name matches the action property passed in.

new Vue({
  channels: {
    ChatChannel: {
      connected() {
        console.log('Connected to the chat channel');
      },
      received(data) {
        console.log('Message received');
      }
    }
  },
  methods: {
    sendMessage() {
      this.$cable.perform({
        channel: 'ChatChannel',
        action: 'send_message',
        data: {
          content: 'Hi'
        }
      });
    }
  },
  mounted() {
    this.$cable.subscribe({
      channel: 'ChatChannel'
    });
  }
});

🐬 Usage with Vuex

ActionCableVue has support for Vuex. All you have to do is setup your store correctly and pass it in during the ActionCableVue plugin setup.

// store.js

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

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
  },
  mutations: {
    sendMessage(state, content){
      this.$cable.perform({
        action: 'send_message',
        data: {
          content
        }
      })
    }
  },
  actions: {
    sendMessage({ commit }, content) {
      commit('sendMessage', content)
    }
  }
});
import store from './store';
import Vue from 'vue';
import ActionCableVue from 'actioncable-vue';

Vue.use(ActionCableVue, {
  debug: true,
  debugLevel: 'all',
  connectionUrl: process.env.WEBSOCKET_HOST,
  connectImmediately: true,
  store
});

💪 Usage with Nuxt.JS

ActionCableVue works just fine with Nuxt.JS. All you need to do is set it up as a client side plugin.

// /plugins/actioncable-vue.js

import Vue from 'vue';
import ActionCableVue from 'actioncable-vue';

if (process.client) {
  Vue.use(ActionCableVue, {
    debug: true,
    debugLevel: 'all',
    connectionUrl: process.env.WEBSOCKET_HOST,
    connectImmediately: true
  });
}

Don't forget to register your plugin.

// nuxt.config.js
/*
 ** Plugins to load before mounting the App
 */
plugins: [{ src: '@/plugins/actioncable-vue', ssr: false }];
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].