赞
踩
uni.connectSocket()
uni.$emit页面通信
项目中使用uni.connectSocket()
创建webSocket的总结,代码可无脑复制,直接使用。
1、main.js 引入vuex
import store from './store';
Vue.prototype.$store = store;
vuex中封装webSocket
2、vuex的:index.js
import Vue from 'vue';
import Vuex from 'vuex';
// 模块
import chat from './modules/chat';
Vue.use(Vuex);
const store = new Vuex.Store({
modules: {
chat,
}
});
export default store;
3、vuex的chat
import Vue from 'vue'; export default { namespaced: true, state: { socketUrl:'wss://api.****.com/wss/default.io', // socke链接 isclose: false, // 是否已连接 reconnections: 0, // 连接次数 heartbeatInterval: null, // 心跳检测 }, mutations: { }, actions: { // 开始或重启即时通讯,全局监听 async start({state, dispatch, rootState}){ // 如果已连接,关闭重新连接 uni.onSocketOpen(()=> { state.isclose = true; }); if (state.isclose) { uni.closeSocket(); uni.onSocketClose((res)=> { clearInterval(state.heartbeatInterval) state.heartbeatInterval = null console.log('已经连接中的Socket关闭成功') }); } // 获取token省略,自行请求接口并赋值,这里只是快速演示如何:创建一个 WebSocket 连接 let token = 'eyJ0****c1Ng' if(token){ let url = `${state.socketUrl}?token=${token}` uni.connectSocket({url}); }else{ console.log('未获取到token'); } // 监听 WebSocket 连接打开事件 uni.onSocketOpen((res)=> { console.log('新创建的Socket连接成功'); }); // 监听WebSocket错误。 uni.onSocketError((res)=> { state.reconnections += 1; if (state.reconnections <= 3) { console.log(`连接失败,正在尝试第${state.reconnections}次连接`); dispatch('start'); }else{ console.error('已尝试3次重新连接均未成功'); } }); // 监听socket接受到服务器的消息事件 uni.onSocketMessage((res)=> { let getData = JSON.parse(res.data) if(getData.event == 'connect'){ // 心跳 state.heartbeatInterval = setInterval(()=>{ uni.sendSocketMessage({data: '{"event":"heartbeat"}'}); },5000) } // 通过uni.$emit触发全局的自定义事件,并在页面中通过uni.$on接收数据 if(getData.event == 'event_talk'){ uni.$emit('getMsg',getData.content); // 更新消息内容 uni.$emit('getList',getData.content); // 更新消息列表 } }); } } }
4、login:登录页面
// 登录接口,登录成功后,存储token,执行chat/start
this.$http.post('/api/').then(res=>{
// 存储token
uni.setStorageSync('token', res.token);
this.$store.dispatch('chat/start');
})
5、聊天页面
<script> export default { data() { return { } }, onUnload() { // 卸载监听 uni.$off('getMsg') uni.$off('getList') }, onLoad() { // 收到更新消息 uni.$on('getMsg', data => { console.log('收到消息的监听getMsg:',data); }) // 收到更新列表 uni.$on('getList', data => { console.log('收到消息的监听getList:',data); }) }, } </script>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。