微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

vue长连接 监听

长连接,也叫Websocket,是指在浏览器和服务器之间建立一条长时间的通讯连接,以便实时地双向数据传输。在Vue中,我们通常使用Vue-Websocket插件来实现这个功能

vue长连接 监听

在使用Vue-Websocket之前,我们需要先安装:npm install vue-native-websocket。然后在main.js中引用:

import VueNativeWebsocket from 'vue-native-websocket'
Vue.use(VueNativeWebsocket,'ws://localhost:3000',{
  reconnection: true,reconnectionAttempts: 5,reconnectionDelay: 3000
})

在这代码中,我们使用Vue.use将VueNativeWebsocket插件引入,并且指定服务端的地址。其中,reconnection表示是否自动重连,reconnectionAttempts表示最大重连次数,reconnectionDelay表示每次重连的间隔时间。

接下来,我们需要在Vue组件中监听WebSocket事件:

export default {
  name: 'MyComponent',mounted() {
    this.websocket.$on('connect',() => {
      console.log('WebSocket连接成功!');
    });
    this.websocket.$on('message',(evt) => {
      console.log(evt.data);
    });
    this.websocket.$on('reconnect',() => {
      console.log('WebSocket重新连接!');
    });
    this.websocket.$on('@R_502_6422@connect',() => {
      console.log('WebSocket连接断开!');
    });
  },methods: {
    sendMsg() {
      var msg = {type: 'message',data: 'hello websocket!'};
      this.websocket.$emit('send',JSON.stringify(msg));
    }
  }
}

在这代码中,我们使用this.websocket.$on监听WebSocket的connect、message、reconnect、@R_502_6422@connect事件。connect事件表示WebSocket连接成功,message事件表示接收到消息,reconnect表示重新连接成功,@R_502_6422@connect表示连接断开。我们也可以使用VueNativeWebsocket提供的$emit方法来发送消息。

除此之外,VueNativeWebsocket还提供了其他一些方法,如:

var websocket = new WebSocket('ws://localhost:3000');
websocket.open();  // 打开WebSocket连接
websocket.close();  // 关闭WebSocket连接
websocket.sendMessage('hello websocket!');  // 发送消息

总之,VueNativeWebsocket插件能够很方便地实现Vue组件与服务端的实时通讯,而且使用简单,非常适合在Vue项目中使用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐