一、新建文件夹websocket,在文件夹中新建index.js文件。
index.js文件如下
import store from '../store'
const socket = {
$ws: null, // websocket对象
lockReturn: false, // 重连锁
timeout: 60 * 1000 * 5, // 5分钟重连
timeoutObj: null, // setInterval()定时器id
timeoutNum: null, // setTimeout()定时器id
// 设置webSocket长连接初始化需要的参数
params: {
baseUrl: 'ws://' + store.state.domain, // base url
page: '', // 页面参数
handleMsg: null // 处理websocket消息的回调函数
},
/**
* @description: 设置webSocket长连接初始化需要的参数
* @param {string} page 页面
* @param {function} handleMsg 处理接收的消息的回调函数
* @return:
*/
setParams(page, handleMsg) {
this.params.page = page
this.params.handleMsg = function (data) {
// 处理接收的消息的回调函数
handleMsg.call(this, data)
}
},
/**
* @description: 初始化webSocket长连接
* @return:
*/
initWebSocket: function () {
let url = this.params.baseUrl + this.params.page + '/' + store.state.token
console.log(url)