0
点赞
收藏
分享

微信扫一扫

uniapp---websocket全局挂载

前提:

在业务的需求下,需要将websocket进行统一的管理。在整个程序的内部使用同一个socke连接进行发送数据。

1.store下的index.js



//引入vue和vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({ //全局变量定义
	state: {
		socketTask: null,
		// 存放websocket中onMessage数据
		websocketData:{}
	},
	mutations: {
		setWebsocketData (state, data) {
		            state.websocketData = data
		        },
	

		/**
		 * @Description:  websocket初始化
		 * @Author:
		 * @param {*} state
		 *
		 */
		//todo:新增
		WEBSOCKET_INIT(state, url) {
			state.socketTask = uni.connectSocket({
				// "ws://127.0.0.1:9002/monitor-web/webSocket", // url是websocket连接ip
				url,
				success() {
					console.log('全局websocket连接成功')
				}
			})
			state.socketTask.onOpen((res) => {
				console.log('全局WebSocket连接正常打开中...!')
				// 注:只有连接正常打开中 ,才能正常收到消息
				state.socketTask.onMessage(res => {
					console.log('收到服务器内容:' + res.data)
				});
			})
			state.socketTast.onOpen(() => dispatch('websocketOnOpen'))
			state.socketTast.onMessage(res => dispatch('websocketOnMessage', res))
			state.socketTast.onClose(e => dispatch('websocketOnClose'))
			state.socketTast.onError(e => dispatch('websocketOnError'))

		},
		/**
		 * @Description:  websocket发送数据
		 * @Author:
		 * @param {*} state
		 *
		 */
		WEBSOCKET_SEND(state, data) {

			state.socketTask.send({
				data,
				async success() {
					console.log('全局消息发送成功',data)
				},
			})

		},
		WEBSOCKET_CLOSE(state) {
			if (!state.socketTask) return
			state.socketTask.close({
				success(res) {
					console.log('全局websocket关闭成功', res)
				},
				fail(err) {
					console.log('全局websocket关闭失败', err)
				}
			})
		},
		WEBSOCKET_ONMESSAGE(state) {

			state.socketTask.onMessage({

					console.log('全局websocket关闭成功', res)


			})
		},
	},
	actions: {
		WEBSOCKET_INIT({
						   commit
					   }, url) {
			commit('WEBSOCKET_INIT', url)
		},
		WEBSOCKET_SEND({
						   commit
					   }, data) {
			commit('WEBSOCKET_SEND', data)
		},
		WEBSOCKET_CLOSE({
						 commit
					 }) {
			commit('WEBSOCKET_CLOSE')
		},
		WEBSOCKET_ONMESSAGE({
						 commit
					 }) {
			commit('WEBSOCKET_CLOSE')
		}
	}

})
export default store

2main.js中进行全局引入store文件

//全局挂载store
import store from './store'
Vue.prototype.$store = store

3.app.vue 全局使用,初始化websocket

//当 uni-app 启动,或从后台进入前台显示
onShow: function() {
  if(this.$store.state.socketTask==null){
      this.$store.dispatch('WEBSOCKET_INIT', 'ws://192.168.96.90:9002/monitor-web/webSocket')

  }
		},
//当 uni-app 从前台进入后台
onHide: function() {
  //关闭链接
  this.$store.dispatch('CLOSE_SOCKET')
},

4.具体业务,发送socket数据

<button @click="test">测试全局发送变量</button>

// 点击发送socket数据
test(){
    this.$store.dispatch('WEBSOCKET_SEND', "jsonString")
}
举报

相关推荐

0 条评论