「短文」如何在 Vue 中复制文本到剪贴板
November 04, 2022
1 min
当您想要显示数据的实时变化时,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"); });
注:本文属于原创文章,版权属于「前端达人」公众号及 qianduandaren.com 所有,未经授权,谢绝一切形式的转载