Giter Club home page Giter Club logo

actioncable-vue's Introduction

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

๐Ÿš€ Installation

npm install actioncable-vue --save
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',
  connectImmediately: true,
});

new Vue({
  router,
  store,
  render: h => h(App)
}).$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 null Required ActionCable websocket server url
connectImmediately Boolean true Optional ActionCable connects to your server immediately. If false, ActionCable connects on the first subscription.

๐ŸŒˆ Component Level Usage

If you want to listen channel events from your Vue component, you need to add a `channels` object in the Vue component. 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'
    });
  }
});

โœจ Subscriptions

1. Subscribing to a channel

Requires that you have an object defined in your component's channels object 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'
    });
  }
});

โ™ฃ 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 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 }];

actioncable-vue's People

Contributors

mclintprojects avatar

Watchers

 avatar  avatar

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.