首页与我联系

「短文」如何在 Vue 中使用 Websockets

By 前端达人
Published in 3-Vue
September 21, 2022
1 min read
「短文」如何在 Vue 中使用 Websockets

当您想要显示数据的实时变化时,WebSockets 是一个很好的工具。例如,服务器可以将股票市场价格变化推送给客户端,而不是客户端需要通过 HTTP 请求请求变化。下面您是一个简单的 Vue 应用程序示例,该示例向用户显示当前时间以及用户可以在其中向 websocket 发送简单消息。

const app = new Vue({
    data: () => ({ time: null }),
    template: `
      <div>
        <h2>{{time}}</h2>
      </div>
    `,
    mounted: function(){
      let connection = new WebSocket('ws://localhost:3000/');
      connection.onmessage = (event) => {
        // Vue data binding means you don't need any extra work to
        // update your UI. Just set the `time` and Vue will automatically
        // update the `<h2>`.
        this.time = event.data;
      }
    }
  });
  app.$mount("#content");

下面是一个示例 websocket 服务端代码,您可以将其与上述 Vue 代码一起结合使用,体验下 websocket:

"use strict";

const serverPort = 3000;
const express = require("express");
const http = require("http");
const WebSocket = require("ws");

const app = express();
const server = http.createServer(app);
const websocketServer =new WebSocket.Server({ server });

//when a websocket connection is established
websocketServer.on("connection", (webSocketClient) => {
// send feedback to the incoming connection
  webSocketClient.send("The time is: ");
  setInterval(() => {
let time =new Date();
    webSocketClient.send("The time is: " + time.toTimeString());
  }, 1000);
});

//start the web server
server.listen(3000, () => {
  console.log("Websocket server started on port 3000");
});

前端达人公众号.jpg

注:本文属于原创文章,版权属于「前端达人」公众号及 qianduandaren.com 所有,未经授权,谢绝一切形式的转载


Tags

vuebasic
Previous Article
「短文」1 分钟学 6 个常见的 DOM 基础操作(十)
前端达人

前端达人

专注前端知识分享

相关文章

「短文」如何在 Vue 中复制文本到剪贴板
November 04, 2022
1 min

前端站点

VUE官网React官网TypeScript官网

公众号:前端达人

前端达人公众号