vue+actioncable实现通信

在rails5之后新增了actioncable实现websocket。通过它可以很方便的搭建websocket服务地端代码,和rails项目的其他功能配合使用非常的方便。具体的服务器端和coffeescript结合的方法此处不做介绍,需要的可以参考作者的文章。
actioncable-examples
actioncable

在vue中使用actioncable,首先需要安装相应的依赖

yarn add actioncable

在vue项目的启动文件中引入actioncable

import ActionCable from "actioncable" // import actioncable
...
Vue.prototype.$cable = ActionCable.createConsumer("ws://localhost:3000/cable"); // create client
...
// 在后续的组件中可以直接使用this.$cable

ws.vue

<template>
  <div class="container">
    <button @click="wsLogin">登录(ws)</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      channel: {}, // 当前订阅的频道
    }
  },
  created() {
    this.channel = this.$cable.subscriptions.create('ChatRoomChannel', {
        connected() {
          console.log('client connected to server!')
        },
        disconnected() {
          console.log('client disconnected from server!')
        },
        received(data) {
          console.group('received data from server');
          console.log(data);
          console.groupEnd();
        },
      });
  },
  methods: {
    wsLogin() {
        // 向服务器端发送消息
        this.channel.perform('login', {
          user: '赵医生',
        });
      },
  }
}
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容