import Vue from 'vue' import Vuex from 'vuex' import {loginUserId} from "../common/tool"; Vue.use(Vuex) export default new Vuex.Store({ state: { socketTask: null, isOpenSocket:false, eventlist: {}, unread: [] }, mutations: { WEBSOCKET_INIT(state, url) { // 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】 state.socketTask = uni.connectSocket({ url, // 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】 success(data) { state.isOpenSocket = false; // console.log("websocket连接成功"); }, }); // 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】 state.socketTask.onOpen((res) => { // console.log("WebSocket连接正常打开中...!"); state.isOpenSocket = true; state.socketTask.send({ data: '[join]' + 'mobile-'+loginUserId, async success() { // console.log("{" + p + "}==》消息发送成功"); }, }); // 注:只有连接正常打开中 ,才能正常收到消息 state.socketTask.onMessage((res) => { // console.log("收到服务器内容:" , JSON.parse(res.data)); state.eventlist = JSON.parse(res.data) // state.unread.push(JSON.parse(res.data)) if (state.eventlist.USER_ID === loginUserId) { var innerAudio = uni.createInnerAudioContext(); innerAudio.autoplay = true; innerAudio.loop = true; innerAudio.src = '../../static/audio/alarm.mp3'; innerAudio.onPlay(() => { // console.log('开始播放'); }); innerAudio.onError((e) => { console.log(e); // console.log(e.errMsg); // console.log(e.errCode); }); if (state.eventlist.MESSAGE) { uni.showModal({ title: '警告', content: state.eventlist.MESSAGE, showCancel: false, confirmText: '确定', success: res => { if (res.confirm) { innerAudio.stop() innerAudio = null } } }) } } }); }); state.socketTask.onClose((res) => { state.isOpenSocket = false; }) }, WEBSOCKET_SEND(state, p) { state.socketTask.send({ data: p, async success() { // console.log("{" + p + "}==》消息发送成功"); }, }); }, }, actions: { WEBSOCKET_INIT({ commit }, url) { commit('WEBSOCKET_INIT', url) }, WEBSOCKET_SEND({ commit }, p) { commit('WEBSOCKET_SEND', p) } } })