uni-app连接websocket(vuex)
- 项目根目录下创建store文件夹---->创建index.js文件
2.将store挂载到vue原型
import Vue from 'vue'
import App from './App'
import uView from "uview-ui";
import store from './store'
Vue.use(uView);
Vue.prototype.$store = store
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App,
store
})
app.$mount()
3.编写store文件夹下index.js文件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
socketTask: null,
is_open_socket: false
},
getters: {
},
mutations: {
connectSocketInit(state, is_open_socket) {
this.state.socketTask = uni.connectSocket({
url: "wss://www.xxx.xxx/socket/websocket",
success(data) {
console.log("websocket连接成功", data);
},
});
this.state.socketTask.onOpen((res) => {
const loginObj = JSON.parse(uni.getStorageSync('loginObj'))
this.state.is_open_socket = is_open_socket;
this.state.socketTask.send({
data: JSON.stringify({
"key": "call_scrollorder_subscribe",
"user_id": loginObj.id
}),
async success() {
console.log("消息发送成功");
},
});
this.state.socketTask.onMessage((res) => {
const result = JSON.parse(res.data).result
console.log(result)
});
})
this.state.socketTask.onClose(() => {
console.log("已经被关闭了")
})
},
closeSocket(state, is_open_socket) {
console.log(this.state)
const _this = this
this.state.socketTask.close({
success(res) {
console.log("关闭成功", res)
_this.state.is_open_socket = is_open_socket
},
fail(err) {
}
})
}
},
actions: {}
})
export default store
3.连接websocket
this.$store.commit('connectSocketInit',true)
4.关闭websocket
this.$store.commit('closeSocket',false)
|