0
点赞
收藏
分享

微信扫一扫

论文阅读(十二):Attention is All You Need

快乐小鱼儿_9911 2024-10-15 阅读 13

一、单文件中引入使用

<template></template>
<script>
    export default {
        websocket: true, // 标志需要使用WebSocket
        data () {
            return {
                ws: null
            }
        },
        created () {
            this.ws = new WebSocket('ws://127.0.0.1:8000'); // ws服务地址
            this.ws.onopen = () => {
                // 接收服务端消息
                this.ws.onmessage = res => {
                    console.log(res.data);
                    // 注:res.data是字符串类型,有需要可通JSON.parse进行转换
                }
                // 发送消息到服务端
                this.ws.send('测试数据');
                // 注:发送的数据需要是字符串类型,有需要可通过JSON.stringify转换
            }
        },
        beforeDestroy () {
            if (this.ws) {
                this.ws.close(); // 断开服务连接
                this.ws = null;
            }
        }
    }
</script>

二、全局引入使用

1、封装websocket.js

const WebSocketPlugin = {
  install(Vue) {
    let ws = null;
    Vue.prototype.$websocket = {
      init (url) {
        ws = new WebSocket(url);
      },
      send(message) {
        if (ws && ws.readyState === WebSocket.OPEN) {
          ws.send(message);
        }
      },
      onMessage(callback) {
        ws && (ws.onmessage = callback);
      },
      onOpen(callback) {
        ws && (ws.onopen = callback);
      },
      onClose() {
        ws && ws.close();
      },
      onError(callback) {
        ws && (ws.onerror = callback);
      }
    }
  }
}
export default WebSocketPlugin;

main.js全局引入

import Vue from "vue";
import WebSocketPlugin from './websocket.js';
Vue.use(WebSocketPlugin);

2、页面使用

<template>
</template>
<script>
    export default {
        websocket: true, // 标志需要使用WebSocket
        created () {
            this.$websocket.init('ws://127.0.0.1:8000');
            this.$websocket.onOpen(() => {
                // 接收服务端消息
                this.$websocket.onMessage(res => {
                    console.log(res.data);
                })
                // 发送消息到服务端
                this.$websocket.send('测试数据');
            })
        },
        beforeDestroy () {
            this.$websocket.onClose();
        }
    }
</script>
举报

相关推荐

0 条评论