123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- import Vue from 'vue'
- import Vuex from 'vuex'
- Vue.use(Vuex)
- const store = new Vuex.Store({
- state: {
- socketTask: null,
- websocketData: {}, // 存放从后端接收到的websocket数据
- },
- mutations: {
- setWebsocketData(state, data) {
- state.websocketData = data
- }
- },
- actions: {
- websocketInit({
- state,
- dispatch
- }, url) {
- state.socketTask = uni.connectSocket({
- url, // url是websocket连接ip
- success: () => {
- // console.log('WebSocket连接成功!')
- },
- fail: e => {
- setTimeout(() => {
- dispatch('websocketInit', url)
- }, 3000)
- // console.log('连接失败' + e)
- }
- })
- state.socketTask.onOpen(() => dispatch('websocketOnOpen'))
- state.socketTask.onMessage(res => dispatch('websocketOnMessage', res))
- state.socketTask.onClose(e => dispatch('websocketOnClose', url));
- state.socketTask.onError(e => dispatch('websocketOnError'));
- },
- websocketOnOpen({
- commit
- }) {
- // console.log('WebSocket连接正常打开中...!')
- },
- // 收到数据
- websocketOnMessage({
- commit
- }, res) {
- let data;
- try {
- data = JSON.parse(res.data)
- } catch {
- data = {
- content: res.data
- }
- }
- commit('setWebsocketData', data);
- },
- websocketOnClose({
- commit,
- dispatch
- }, url) {
- setTimeout(() => {
- dispatch('websocketInit', url)
- }, 3000)
- // console.log('WebSocket连接关闭')
- },
- websocketOnError({
- commit,
- dispatch
- }) {
- // console.log('WebSocket连接错误')
- },
- websocketClose({
- state
- }) {
- if (!state.socketTask) return
- state.socketTast.close({
- success(res) {
- // console.log('关闭成功', res)
- },
- fail(err) {
- // console.log('关闭失败', err)
- }
- })
- },
- // 发送数据
- websocketSend({
- state
- }, data) {
- uni.sendSocketMessage({
- data,
- success: res => {
- // console.log('发送成功', res)
- },
- fail: e => {
- // console.log('发送失败', e)
- }
- })
- }
- }
- })
- export default store
|