apk需要实时数据展示于是就全局封装了个webSocket
1.创建一个webSocket的js文件
/**
* 注册websocket
* @mask 支持promise返回,也支持回调返回
* @param path websocket地址
* @param onMsg 接收推送的回调函数
* @param onOpen 连接消息
* @param onErr 错误消息
* @returns {Promise}
*/
export function websocket(opt = {
path: '', onMsg: () => {
}, onOpen: () => {
}, onErr: () => {
}
}) {
return new Promise((resolve, reject) => {
console.log(opt.path);
try {
let ws = new WebSocket(opt.path)
let heartTimer
// 绑定消息
ws.onmessage = (msg) => {
if (msg.data !== 'heart') { // 非心跳包返回
if (opt.onMsg) opt.onMsg(msg, ws)
resolve(msg, ws);
}
}
ws.onopen = (event) => { // 绑定连接消息
if (opt.onOpen) opt.onOpen(event, ws);
heartTimer = setInterval(() => { // 连接成功后发2秒心跳包
ws.send('heart')
}, 2000)
}
ws.onerror = (err) => { // 绑定错误消息
console.log(err);
if (opt.onErr) opt.onErr(err, ws)
reject(err, ws);
clearTimeout(heartTimer)
}
ws.onclose = () => {
ws.close();
clearTimeout(heartTimer)
}
} catch (e) {
console.log(e);
reject();
}
})
}
export default websocket;
2.在引入公共函数的js文件中引入webSocket.js
import websocket from "./libs/function/webSocket.js";
// $cu挂载到uni对象上
const $cu = {
websocket,
}
uni.$cu = $cu
const install = Vue => {
Vue.prototype.$cu = $cu
uni.$cu.eventBus = new Vue();
}
export default {
install
}
3.在main.js文件中用vue实例上挂载这些函数
import cuView from "./cuview-ui/index";
Vue.use(cuView)
4.在需要建立连接的页面使用,用data定义所需要的数据,在初始化页面时调用该方法
data() {
return {
obj: {
path: `ws://${this.$store.state.vuex_http.baseUrl}:10011/app_dev_message`,
onMsg: (msg) => {
this.onit()
console.log('数据更新了');
}, onOpen: (msg) => {
console.log('建立连接成功');
}, onErr: () => {
console.log('建立连接失败');
}
}
}
},
onLoad() {
this.$cu.websocket(this.obj)
},