一、单文件中引入使用
<template></template>
<script>export default {websocket: true, // 标志需要使用WebSocketdata () {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, // 标志需要使用WebSocketcreated () {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>