官方包 · 框架

实时 WebSocket 的 Vue 组合式函数

Vue 3 和 Vue 2.7 上处理事件、在线状态、客户端事件和连接状态的组合式函数。频道名可以是 ref,订阅会随之变化。

  • useEvent、usePresence、useTrigger 和 useConnectionState,所有组件共用一条连接。
  • 服务端渲染下也安全:服务端不会建立连接。
  • 可与 Laravel Echo 配合使用:把 Echo 的连接作为客户端传入即可。

登录后,示例代码会自动填入您的集群主机。 登录

  1. 安装

    npm install @hibira-io/vue pusher-js
  2. 配置

    import { createApp } from 'vue';
    import { createHibira } from '@hibira-io/vue';
    
    createApp(App)
      .use(createHibira({
        appKey: import.meta.env.VITE_HIBIRA_KEY,
        options: {
          wsHost: 'ws.hibira.io',
          channelAuthorization: { endpoint: '/api/hibira/auth', transport: 'ajax' },
        },
      }))
      .mount('#app');
  3. 使用

    <script setup>
    import { ref } from 'vue';
    import { useEvent, usePresence } from '@hibira-io/vue';
    
    const orders = ref([]);
    useEvent('orders', 'order.created', (order) => orders.value.unshift(order));
    const { count } = usePresence('presence-dashboard');
    </script>

开始之前

  • Free 套餐需要把页面加载的每个来源都加入应用的“允许的来源”(开发时是 http://localhost:3000,之后是您的域名)。"*" 需要付费套餐。
  • 私有频道和 presence 频道需要后端提供授权端点,用应用密钥签名订阅,做法与 pusher-js 相同。

请使用控制台中应用的 Key;Secret 只放在你的服务器上。频道、事件与授权端点的用法与 Pusher 完全相同。 免费创建账号 →