vue websocket 实现页面实时刷新

最近公司项目需求后台web端要做实时能看到用户的登录状态以及所在位置,说白了就是要做数据实时刷新。
直接上代码吧!

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Websocket demos</title>
  <script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
</head>

<body>
  <div id="app">
    <input type="text" v-model.trim="msg" @keyup.enter="echo">
    <button @click="echo">发送</button>
  </div>

  <script>
    /* global Vue, WebSocket */
    var ws = null

    new Vue({
      el: '#app',
      data: {
        msg: ''
      },
      methods: {
        echo: function () {
          if (!this.msg) return
          console.log('WebSocket发送消息: ' + this.msg)
          ws.send(this.msg)
        },
        initWebSocket: function (params) {
          // ws = new WebSocket('wss://echo.websocket.org/')
          ws = new WebSocket("ws://30.30.99.151:9093/websocket");
          // var ws = new WebSocket("ws://localhost:8096/websocket/111405");
          ws.onopen = function (e) {
            console.log('WebSocket已经打开: ')
            console.log(e)
          }
          ws.onmessage = function (e) {
            console.log('WebSocket收到消息: ' + e.data)
          }
          ws.onclose = function (e) {
            console.log('WebSocket关闭: ')
            console.log(e)
          }
          ws.onerror = function (e) {
            console.log('WebSocket发生错误: ')
            console.log(e)
          }
        }
      },
      created: function () {
        this.initWebSocket()
      }
    })
  </script>
</body>

</html>

页面效果展示
在这里插入图片描述

vue websocket 线上测试地址

http://www.websocket-test.com/
在这里插入图片描述

Logo

前往低代码交流专区

更多推荐