Vue3 可以使用 WebSocket 来实现实时通信。以下是一个简单的例子:

  1. 首先,安装 WebSocket 库:
npm install vue-native-websocket
  1. 在 main.js 中引入 WebSocket 插件,并配置 WebSocket 连接:
import VueNativeSock from 'vue-native-websocket'

Vue.use(VueNativeSock, 'ws://localhost:8080', {
  format: 'json',
  store: store, // 如果你使用了 Vuex,可以将 store 传递给 WebSocket 插件
  reconnection: true, // 是否自动重新连接
  reconnectionAttempts: 5, // 重新连接尝试次数
  reconnectionDelay: 3000, // 重新连接延迟(毫秒)
})
  1. 在 Vue 组件中使用 WebSocket:
export default {
  mounted() {
    this.$socket.addEventListener('message', this.handleMessage)
  },
  methods: {
    handleMessage(event) {
      // 处理接收到的消息
    },
    sendMessage() {
      this.$socket.send(JSON.stringify({ message: 'Hello' }))
    },
  },
}

在上面的例子中,我们在组件的 mounted 钩子函数中监听 message 事件,然后在 handleMessage 方法中处理接收到的消息。sendMessage 方法发送消息到服务器。

这只是一个简单的示例,你可以根据你的需求进行扩展和定制。请注意,WebSocket 连接的 URL 和其他配置可能需要根据你的实际情况进行修改。


原文地址: https://www.cveoy.top/t/topic/qeM8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录