美文网首页
vue+actioncable实现通信

vue+actioncable实现通信

作者: 李傲娢 | 来源:发表于2018-10-30 21:14 被阅读25次

    在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>
    

    相关文章

      网友评论

          本文标题:vue+actioncable实现通信

          本文链接:https://www.haomeiwen.com/subject/xqyntqtx.html