0
点赞
收藏
分享

微信扫一扫

用html写早安,晚安动画

大自然在召唤 04-10 13:30 阅读 2

原生 WebSocket API

创建 WebSocket 连接

在Vue组件中,你可以使用createdmounted生命周期钩子来创建WebSocket连接。例如:

export default {
  data() {
    return {
      socket: null,
      messages: []
    };
  },
  created() {
    this.socket = new WebSocket('ws://localhost:8765');

    this.socket.onopen = () => {
      console.log('WebSocket connected');
    };

    this.socket.onmessage = (event) => {
      this.messages.push(event.data);
    };
  },
  methods: {
    sendMessage(message) {
      this.socket.send(message);
    }
  }
};
发送消息

你可以在Vue组件的方法中调用socket.send()方法来发送消息。例如,假设你有一个发送消息的按钮,你可以这样处理点击事件:

<button @click="sendMessage('Hello WebSocket')">Send Message</button>

使用封装的 WebSocket 库

你也可以使用一些封装好的WebSocket库,例如vue-native-websocketvue-socket.io。这些库提供了更加便捷的API来处理WebSocket连接。

vue-native-websocket
npm install vue-native-websocket
import VueNativeSock from 'vue-native-websocket';

Vue.use(VueNativeSock, 'ws://localhost:8765', {
  format: 'json',
  reconnection: true, // 是否重新连接
  reconnectionAttempts: 5, // 重新连接次数
  reconnectionDelay: 3000 // 重新连接间隔时间(毫秒)
});

然后你可以在Vue组件中直接使用this.$socket访问WebSocket连接,发送和接收消息。

vue-socket.io
npm install vue-socket.io
import VueSocketIO from 'vue-socket.io';

Vue.use(new VueSocketIO({
  debug: true,
  connection: 'http://localhost:8765'
}));

然后你可以在Vue组件中通过this.$socket访问Socket.io连接,发送和接收消息。

举报

相关推荐

0 条评论